Lazar Lazar - 1 year ago 86
C Question

Type conversion confusion in C

#include <stdio.h>

int main()
char c = 255;
if (c > 128)
printf("This is unsigned number %d\n", c);
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?

Answer Source

This isn't well-defined behavior. The relevant part of the standard ยง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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download