Integer promotion in C
Small types promote to int, and mixing signed with unsigned converts the signed one.
#include <stdio.h>
void promotion(void) {
char a = 100;
char b = 100;
int sum = a + b;
signed int negative = -1;
unsigned int positive = 1;
printf("sum %d, fits in char: %d\n", sum, sum <= 127);
printf("-1 < 1u is %d\n", negative < positive);
printf("cast fixes it: %d\n", negative < (int) positive);
size_t length = 3;
for (int i = (int) length - 1; i >= 0; i--) {
printf("%d ", i);
}
printf("\n");
}
How it works
charandshortare promoted tointbefore arithmetic.- A signed value compared against unsigned becomes unsigned.
- That is why
-1 < 1uis false, which surprises everyone once.
Keywords and builtins used here
charforintpromotionsignedsize_tunsignedvoid
The run, in numbers
- Lines
- 20
- Characters to type
- 405
- Tokens
- 125
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 94 seconds.
Step 7 of 7 in Variables & types, step 7 of 35 in Language basics.