C Programming Basics

uint8_t x = 250;
for (int i = 0; i < 10; i++)
    x++;
printf("%d\n", x);

uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above, which increments x ten times, is executed?

  1. A4
  2. B255
  3. C260
Show answer and explanation

Answer: A. 4

uint8_t can represent 0 to 255. The standard specifies that a value that does not fit in an unsigned integer type becomes its remainder modulo 2⁸ = 256, so counting up by 1 from 250, the value after 255 goes back to 0. After 10 increments, the result is 250 + 10 = 260 modulo 256, which is 4. In contrast, overflow in signed integer arithmetic is undefined behavior.

  • A. Correct. It is 260 modulo 256, which is 4.
  • B. This is the value obtained by assuming it stops (saturates) at the maximum 255. Unsigned integer types wrap back toward 0.
  • C. This is 250 plus 10 without considering overflow. uint8_t cannot hold values of 256 or more.
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. unsigned char is 8 bits and int is 32 bits. Which of the following is the output when the code above is executed?
  2. 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?
  3. int and unsigned int are 32 bits. Which of the following is the result when the code above is executed?
  4. unsigned int is 32 bits. Which of the following describes the behavior when the code above is executed?
  5. 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?