Search code examples
ctype-conversionunsignedsigned

Type conversion confusion in C


#include <stdio.h>

int main()
{
    char c = 255;
    if (c > 128)
    {
        printf("This is unsigned number %d\n", c);
    }
    else
    {
        printf("This is signed number %d\n", c);
    }
}

What happens in this case when we initialize an signed char which have range from -127 to 128 with 255? It doesn't wrap around because it is undefined behavior, but what really happens?

I am getting -1 result, but how and why?


Solution

  • This isn't well-defined behavior. The relevant part of the standard 6.3.1.3 §3:

    Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

    This means that the result depends on the compiler. Probably, your compiler attempts some sort of wrap-around based on two's complement - that's the most common behavior. It is not undefined behavior.

    Please note that the char type could be either signed or unsigned, that also depends on the compiler.