werther werther - 18 days ago 5
C Question

Overflow not beeing recognized, p is not printing warning

I'm having a problem with my little c program.

I'm trying to print out a warning if an overflow occurs, I'm using the limits.h library to recognise an overflow with INT_MAX.
I guess the problem is in my if loop, but I can't really find the problem...

#include<stdio.h>
#include<limits.h>

int main()
{
int x = 1627964;
int y = 9;

for(int i=1; i<y; ++i){
x*= i; // x= x * i
printf("%d * %d \n",x , i+1);
if(x >= INT_MAX){
printf("An Overflow has occured!\n");
return 0;
break;
}
}
}


I think the overflow occurs after multiplying with 7:

1627964 * 2
3255928 * 3
9767784 * 4
39071136 * 5
195355680 * 6
1172134080 * 7
-384996032 * 8
1214999040 * 9


I can't really tell why the warning is not printed out...

Some help would be really appreciated, thanks :)

Answer

x == INT_MAX only tests if x is exactly equal to INT_MAX. Not less, not more, exactly equal.

What you should be testing for is signed integer overflow, which happens when you multiply by 1627964 by 8: if (x==INT_MAX || x < 0) - the sign bit gets incremented which makes your value negative.