What is the output of this code snippet running on an 8-bit microcontroller where char is 8 bits?
#include <stdio.h> int main() { unsigned char a = 250; signed char b = 10; unsigned char c = a + b; printf("%u\n", c); return 0; }
Remember that unsigned char wraps around at 255.
Adding 250 + 10 = 260. Since unsigned char can only hold 0-255, it wraps around modulo 256. 260 - 256 = 4.
What is the output of this code snippet on an 8-bit MCU where char is signed 8-bit?
#include <stdio.h> int main() { signed char x = 127; signed char y = 1; signed char z = x + y; printf("%d\n", z); return 0; }
Think about signed overflow and two's complement wrap-around.
Adding 127 + 1 causes signed overflow. On 8-bit signed char, max is 127, so it wraps to -128.
Consider this code on an 8-bit MCU:
#include <stdio.h>
int main() {
unsigned char a = 5;
unsigned char b = 10;
unsigned char c = a - b;
printf("%u\n", c);
return 0;
}Why does it print 251 instead of a negative number?
Think about how unsigned arithmetic works on small fixed-size types.
Unsigned arithmetic wraps modulo 256 on 8-bit types. So 5 - 10 = -5 mod 256 = 251.
What is the output of this code on an 8-bit MCU?
#include <stdio.h> int main() { signed char a = -1; unsigned char b = 255; if (a == b) { printf("Equal\n"); } else { printf("Not Equal\n"); } return 0; }
Integer promotions: both char types promote to signed int. -1 != 255.
Both operands undergo integer promotions to int: signed char -1 becomes int -1 (sign-extended), unsigned char 255 becomes int 255. Since -1 != 255, it prints "Not Equal".
On an 8-bit MCU, why does C define signed integer overflow as undefined behavior, but unsigned integer overflow wraps around modulo 256?
Think about the C language standard and hardware behavior.
The C standard defines unsigned overflow as modulo arithmetic to allow predictable wrap-around. Signed overflow is undefined to allow compilers to optimize and because hardware behavior can vary.