ProgrammingHardGATE CS

What is printed? Assume unsigned int is 32 bits and unsigned char is 8 bits.

What is printed? Assume unsigned int is 32 bits and unsigned char is 8 bits.
#include <stdio.h>
int main(void) {
    unsigned int x = 1u << 31;
    unsigned int y = x * 2 + (x >> 31);
    unsigned char z = (unsigned char)(y + 255);
    printf("%u %u", y, z);
    return 0;
}
  1. A. 1 255
  2. B. 0 255
  3. C. 1 0
  4. D. 2147483649 0

Correct answer: C. 1 0

x = 2^31, so x * 2 wraps to 0 in unsigned arithmetic, and x >> 31 is 1, giving y = 1. Then y + 255 = 256, and converting to unsigned char keeps the low 8 bits: 0.

More C Programming questions

Exams that ask this topic