0

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 :)

Barmar
  • 741,623
  • 53
  • 500
  • 612
werther
  • 47
  • 7

3 Answers3

0

Only unsigned int has defined overflow behavior, signed int does not, so compiler could throw away half of your code if it detect it. Anyway in your code int never will be bigger than INT_MAX because on overflow it should be negative value.

Mateusz Drost
  • 1,171
  • 10
  • 23
0

If you try int max / i < x for the overflow ?

Aodren BARY
  • 121
  • 9
-3

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.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85