Search code examples
ctypes

Negative power of 2


I am learning the characteristics of the different data type. For example, this program increasingly prints the power of 2 with four different formats: integer, unsigned integer, hexadecimal, octal

#include<stdio.h>
int main(int argc, char *argv[]){
        int i, val = 1;
        for (i = 1; i < 35; ++i) {
                printf("%15d%15u%15x%15o\n", val, val, val, val);
        val *= 2;
        }
    return 0;
}

It works. unsigned goes up to 2147483648. integer goes up to -2147483648. But why does it become negative?

I have a theory: is it because the maximum signed integer we can represent on a 32 bit machine is 2147483647? If so, why does it return the negative number?


Solution

  • First of all, you should understand that this program is undefined. It causes signed integer overflow, and this is declared undefined in the C Standard.

    The technical reason is that no behavior can be predicted as different representations are allowed for negative numbers and there could even be padding bits in the representation.

    The most probable reason you see a negative number in your case is that your machine uses 2's complement (look it up) to represent negative numbers while arithmetics operate on bits without overflow checks. Therefore, the highest bit is the sign bit, and if your value overflows into this bit, it turns negative.