What is printed by this C code: unsigned char c = 255; c = c + 1; printf(“%d”, c);?
Correct answer C. 0
Explanation
c + 1 is computed as int 256, but storing it back into an unsigned char (8 bits on mainstream platforms) reduces the value modulo 256, giving 0. Unsigned arithmetic and conversion to unsigned types always wrap around in this defined way, so this is not undefined behaviour. 256 would be printed only if the result were kept in an int, and -1 would need a signed type.
Answer checked How we write and check questions
Discussion