c / expert
Snippet
Implicit Integer Promotion and the Bitwise NOT
In C, arithmetic operations on types smaller than 'int' (like char or short) trigger 'integer promotion', converting the operand to an 'int' first. Performing a bitwise NOT (~) on an unsigned char 0xFF results in an int (typically 0xFFFFFF00 on 32-bit systems) rather than 0x00, which is a frequent source of bugs in low-level bit manipulation.
snippet.c
1
2
3
4
5
6
unsigned char val = 0xFF;if (~val == 0) {// This block will NOT execute} else if ((unsigned char)~val == 0) {// This block WILL execute}
Breakdown
1
~val == 0
The promoted 'val' (0x000000FF) becomes (0xFFFFFF00) after inversion, which is not equal to zero.
2
(unsigned char)~val
Casting back to unsigned char truncates the result to 8 bits, yielding 0x00.