C Programming Basics
unsigned char a = 200, b = 100;
int s = a + b;
unsigned char c = a + b;
printf("%d %d\n", s, c);unsigned char is 8 bits and int is 32 bits. Which of the following is the output when the code above is executed?
- A44 44
- B300 44
- C300 300
Show answer and explanation
Answer: B. 300 44
In C, values of types smaller than int (such as char and short) are converted to int before arithmetic (integer promotion). So a + b is computed not in 8 bits but as an int, giving 300, and the int s receives 300 unchanged. When assigned to the 8-bit c, it is converted to 300 modulo 256, which is 44. Even on an 8-bit microcontroller, the standard has intermediate calculations in an expression done at the width of int.
- A. The addition is done in int, so s receives 300. This is the value obtained if the calculation stays in 8 bits.
- B. Correct. s is 300 computed as an int, and c is 300 modulo 256, which is 44.
- C. An unsigned char c cannot hold values of 256 or more, and 300 is converted to 44.