According to this question on stack overflow, signed integer overflow is not defined -


I wrote this code to verify it -

#include <stdio.h>

int main(void)
     // defining a signed integer with value (2^31) - 2
    signed int i = 2147483646;
    // A loop which executes until (2^31) which cannot be reached by an integer
    while (i <= 2147483648) 
        printf("%i\n", i);

        // breaks the code so that it doesn't execture infinitely
        if ( i == -2147483632)

i did get a warning that this loop will execute infinitely but since i added the break line in the code that isnt a problem. So i used the command -w to ignore the warnings. Now when i execute this code using the make commmand line along with -w i get this -

  $ clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow    test.c  -lcrypt -lcs50 -lm -o test -w
    $ ./test

But according me i should've gotten an error since signed integer overflow is not defined. What is the problem here?


while (i <= 2147483648) can be optimized to while (true), that's the infinite loop.

"undefined" behaviour means the compiler is free to do whatever it wants. It might work on some platforms, it might not work on others, it might crash, erase your hard drive, it might send your boss a nasty e-mail (very unlikely). Whatever it is, you don't have any guarantee.

In case of the signed int overflow, I assume there might be systems using 1's complement instead of 2's complement, which differ in the lowest possible value by 1. I don't think there are modern computers using 1's complement.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .