Reputation: 239
I'm confused as to why this does not cause an error.
void f(int I) {
++I;
if (I > INT_MAX) {
printf("OVERFLOW\n");
} else {
printf("NO OVERFLOW\n");
}
}
int main(void) {
f(INT_MAX);
printf("DONE\n");
}
I'm coding in C, and my school defined INT_MAX for us already to be $2^{31} - 1$ I think is what it is.
Upvotes: 0
Views: 87
Reputation: 1074
OVERFLOW
will not be printed in your case. What is happening in your case is that: When your I
is already at the maximum, and if you further increase it using ++I
, it will wrap around to the lowest value. Illustration:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
void f(int I) {
++I;
printf("\nAfter incrementing I: %d\n", I);
if (I > INT_MAX) {
printf("OVERFLOW\n");
} else {
printf("NO OVERFLOW\n");
}
}
int main(void) {
f(INT_MAX);
printf("DONE\n");
}
Output:
After incrementing I: -2147483648
NO OVERFLOW
DONE
Upvotes: 1
Reputation: 414
This can give you NO OVERFLOW on two different routes:
if
is compiled to a simple printf("NO OVERFLOW\n");
.2147483647+1=-2147483648
, which doesn't make sense in maths, but here it's a design feature. This makes adding reasonably large negative numbers to positive numbers work well. Just you need to keep in mind to use the proper type to hold your numbers.(I'm assuming a "normal" 32 bit int, but some architectures use different size, e.g. on AVR8 ints are 16 bit long.)
Upvotes: 1