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?

  1. A44 44
  2. B300 44
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. uint8_t is an 8-bit unsigned integer type and int is 32 bits. Which of the following is the result when the code above is executed?
  2. int and unsigned int are 32 bits. Which of the following is the result when the code above is executed?
  3. unsigned int is 32 bits. Which of the following describes the behavior when the code above is executed?
  4. A program that sets "char c = 200;" and prints c with %d in printf printed −56 when compiled and run with gcc for x86-64 Linux, and 200 with gcc for Arm Linux. Which of the following is the reason for the difference?
  5. Which of the following is the output when the code above, with b++ on the right side of && and ||, is executed?