LearnFrenzy
Sign in Take a free test

Data Types · Find the Error · Question 7

Converting a too-large double to int Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    double population = 8.1e9;      /* world population */
    int people = (int) population;
    printf("%d\n", people);
    return 0;
}
  • A 8.1e9 is not a valid double
  • B The cast should be (long)
  • C 8.1 × 10⁹ is larger than INT_MAX, and converting an out-of-range double to int is undefined behaviour Correct
  • D There is no bug
Correct Answer: Option C

Unlike unsigned conversions, floating-to-integer conversion does not wrap: if the value does not fit, the behaviour is undefined (a sanitizer reports it). Use long long, which holds about 9.2 × 10¹⁸.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links