I would like to know why this piece of code printf char c infinitely:
char c; for (c = 0; c< 256; c++) printf("Char c=%c\n", c); Thanks
Assuming CHAR_BIT is 8 (which it almost always is), a char object cannot represent a value of 256; signed char will max out at 127, while unsigned char will max out at 255.
Signed case
When c is 127 and you add 1, the value "overflows". Because one's-complement and sign-magnitude representations are still a thing on some oddball architectures, the exact result can vary. For two's-complement, it will "wrap around" to -128, whereas for one's-complement it wraps around to -127, and for sign-magnitude it becomes -0.
All of these values are less than 256, so the condition c < 256 is always true.
Because the result can vary based on the platform, the C language definition places no requirements on the compiler to handle signed integer overflow in any particular way - the behavior is left undefined, and any result is equally "correct" as far as the language is concerned. A reasonably smart compiler might be able to detect that the condition will always evaluate to true and issue a warning, and it would be free to do that as far as the language definition is concerned. Or not.
Unsigned case
Unlike the signed case, unsigned integer overflow is well-defined; if c is 255 and you add 1, then the result wraps around back to 0. Again, 0 is less than 256, so c < 256 will always be true.
Because the char data type is only one byte long, and therefore can only hold the values 0-255.
So when c is 255 and you do c++, it becomes 0. Thus, c is always < 256 in the loop.
char is unsigned, which is almost never the case.CHAR_BIT bits, which is at least 8.char!
charvalue is always less than256(providedCHAR_BITis8heh heh).charholds values from 0-255 (or -128-127 when considering the sign bit) ,, so 255+1 wraps back around to 0,, so your conditionc<256is always true.%cto%d, and the answer should be clear.