0

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

https://stackoverflow.com/questions/18195715/why-is-unsigned-integer-overflow-defined-behavior-but-signed-integer-overflow-is

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);
        i++;

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

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
    2147483646
    2147483647
    -2147483648
    -2147483647
    -2147483646
    -2147483645
    -2147483644
    -2147483643
    -2147483642
    -2147483641
    -2147483640
    -2147483639
    -2147483638
    -2147483637
    -2147483636
    -2147483635
    -2147483634
    -2147483633

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

2

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 .