Question.1
A timer counter on an 8-bit MCU accumulates ADC readings:
uint8_t total = 250;
uint8_t sample = 10;
total += sample;
printf("%u", total);What is the output?
This guide helps you understand all the tricky, often misunderstood arithmetic behaviors in C, especially relevant for firmware development where correctness and efficiency matter.
1. Unsigned Integer Overflow (Wraparound)
uint8_t a = 250;
uint8_t b = 10;
uint8_t c = a + b; // c = 4Why?
2. Signed Integer Overflow (Undefined Behavior)
int8_t a = 120;
int8_t b = 10;
int8_t c = a + b; // UBWhy?
3. Unsigned Integer Underflow (Wraparound)
uint8_t a = 5;
uint8_t b = 10;
uint8_t c = a - b; // c = 251Why?
4. Signed Integer Underflow (Undefined Behavior)
int8_t a = -120;
int8_t b = 20;
int8_t c = a - b; // UBWhy?
5. Signed/Unsigned Comparison Trap
int a = -1;
unsigned int b = 1;
if (a < b) // FALSE!Why?
6. Mixing Signed and Unsigned in Addition
uint8_t a = 255;
int8_t b = -1;
int result = a + b; // 254Why?
7. Promotion in Arithmetic (Truncation)
uint8_t a = 250, b = 10;
uint8_t sum = a + b; // sum = 4Why?
8. Division by Zero
int a = 5, b = 0;
int c = a / b; // UndefinedWhy?
9. Modulo by Zero
int a = 10, b = 0;
int c = a % b; // UndefinedWhy?
10. Negative Modulo Behavior
int a = -7, b = 3;
int r = a % b; // -1Why?
11. Invalid Shift Amounts
int a = 1;
int b = -1;
a << b; // Undefined
1 << 40; // Undefined on 32-bitWhy?
12. Left Shift Overflow (Signed)
int8_t a = 64;
a <<= 2; // UBWhy?
13. Right Shift on Negative Values
int8_t a = -4;
int8_t b = a >> 1; // May be -2 or 126Why?
14. Unsigned Loop Trap
uint8_t i;
for (i = 3; i >= 0; i--) // Infinite loop!Why?
15. Pre/Post-Increment Chaos
int i = 1;
int x = i++ + ++i; // UBWhy?
16. Float to Int Precision Loss
float f = 3.9;
int x = f; // x = 3Why?
17. Integer Division Truncates
int a = 5, b = 2;
int result = a / b; // 2Why?
18. Casting Negative to Unsigned
int8_t a = -1;
uint8_t b = (uint8_t)a; // 255Why?
19. Float to Int Conversion
float f = -2.8;
int x = f; // x = -2Why?
20. Overflow in Compound Expressions
uint8_t a = 250, b = 10;
uint8_t c = (a + b) / 2; // c = 2Why?
✔ Fix:
uint16_t temp = a + b;
uint8_t c = temp / 2; // Correct: 130