INT_MAX
declared in limits.h
. Any statement that tries to put a
value larger than INT_MAX
into an int is likely to give
wildly incorrect results.
Now, back to the problem at hand. No matter what digit we try to add
on to the number, there must be room to "shift" the number
over and add a zero on to the end. This can only work if the number is sufficiently smaller than INT_MAX
. In particular:
number * BASE <= INT_MAXThe trouble is that
number * BASE
may, in fact, be too big to represent. So, we don't want to even try doing that calculation. What can we do then? Just adjust the inequality:
number * BASE / BASE <= INT_MAX / BASE number <= INT_MAX / BASEThe use of integer division in the final inequality won't be a problem. See if you can understand why.
Now, we can shift the number over, but then we need to ask whether the digit will fit on to the end of the number. This is even simpler than the last question; we just need to know whether this is true:
shifted_number + digit_value <= INT_MAXAgain, we don't want to actually perform the calculation on the left. Can you figure out how to avoid it as we did above?
If both these checks are passed, the number is not too large to fit.
'3' > '0' '2' < '9' 'C' > 'B' '0' == '0' 'C' != 'c' 'A' < 'Z'What about an inequality like
'C' > '3'
? You should avoid relying on the truth value of this inequality. This is not because the value is not known or specified by the C language. Instead, it's because it's difficult for readers of your code to understand what you're doing if you rely on such facts.
'\n'
?
scanf("%c", &character);
will read a
single character without skipping anything. scanf
does
not skip whitespace when reading characters. It will only skip the
whitespace if you read a number (int or double) or put in a space in
the format string.