tags:

views:

124

answers:

4
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??

+3  A: 

Smells like a homework.

Casting from wide type to narrow type not always work as expected (for you to figure out what exactly wrong).

qrdl
Discussing the bit-depth issues would have been more fun :)
whatnick
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 being 4bytes is debated.
whatnick
+2  A: 

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.

whatnick
It is very bad idea to give detailed answer to the homework question.
qrdl
thanks Nick!but how come the compiler or the program wouldn't generate a warning for this kind of overflow?
Byte order doesn't affect it, since least significant bits are always the same ones, regarding of their in-memory locations.
Pavel Minaev
@metashockwave I consider the question triggering my intiative to search and highlight minor points. The homework will improve the asker if they understand my answer - obviously their tutor/teacher is not upto scratch.
whatnick
@Pavel Minaev MSB/LSB referring to the bit version not the byte version. I do a lot of binary data reads and the interpretation can differ.
whatnick
Still doesn't matter. A least significant bit is still the one which, when set on its own, will produce `(int)1`. ISO C does not provide for any other interpretations, so where that bit is actually located in memory is not relevant.
Pavel Minaev
Assuming the reading and writing systems have the same bit order, if the binary data transmitted across systems things can get confusing.
whatnick
+1  A: 

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.

AraK
but how come the compiler or the program wouldn't generate a warning for this kind of overflow?
Because it's C and we like to play C fast and dirrrrrty.
phoebus
LOL too fast and too furious!
A: 

It also shows two's compliment.

Justin Johnson