int main(void) {
char x;
int y=1280;
x=y;
printf("%d", x);
}
OUTPUT: 0
I remember that int = 4 byte and char is merely 1 byte. So we're trying to squeeze a 4 byte data into a 1 byte space, but why is the output 0??
int main(void) {
char x;
int y=1280;
x=y;
printf("%d", x);
}
OUTPUT: 0
I remember that int = 4 byte and char is merely 1 byte. So we're trying to squeeze a 4 byte data into a 1 byte space, but why is the output 0??
Smells like a homework.
Casting from wide type to narrow type not always work as expected (for you to figure out what exactly wrong).
Integer types are the most confusing in C/C++ compilers. In your case the answer is simple though, the code demonstares overflow. Char is an 8-bit data type which can only have values 0-255 and 256 which requires 9bits to represent will overflow to 0. Here 1280 = 256*5 and the least significant 8-bits are zero , hence when assigned to a char the value is 0. It will be interesting to see what the output is in MSB vs LSB systems.
Casting from a wider type to narrower type, works only if you respect the rules. wihtout of that, you are under the mercy of implementations. So, technically what happens is that the compiler assigns the first byte of y, to x! If y holds more than one byte of information, it is lost. For example, when you have y == 0xFFFFFFFF => x = 0xFF
.