Integer promotion is an implicit conversion in C that converts certain integer types, such as char, signed char, unsigned char, and short, to int or unsigned int before specific operations are performed.
#include <stdio.h>
int main(void)
{
char a = 10;
char b = 20;
int result = a + b;
printf("Result: %d\n", result);
printf("Size of a: %zu byte(s)\n", sizeof(a));
printf("Size of a + b: %zu byte(s)\n", sizeof(a + b));
return 0;
}
Example Output #
On a typical implementation where int occupies four bytes:
Result: 30
Size of a: 1 byte(s)
Size of a + b: 4 byte(s)
Explanation #
The variables a and b have type char. However, in the expression:
a + b
both operands undergo integer promotion before addition. On a typical implementation, they are promoted to int, so the addition is performed using int values.
The sizeof operator shows the difference:
sizeof(a)
returns the size of the char object, while:
sizeof(a + b)
returns the size of the expression’s type, which is int in this example.
Integer Promotion Rules #
| Original type | Promotion result |
|---|---|
char |
int or unsigned int |
signed char |
int |
unsigned char |
int or unsigned int |
short |
int or unsigned int |
unsigned short |
int or unsigned int |
_Bool |
int |
| Enumeration type | Determined by the applicable integer-promotion rules |
A type is promoted to int if int can represent all its values. Otherwise, it is promoted to unsigned int.
Integer promotion does not necessarily increase the size of every operand in every implementation. The result depends on the source type and the ranges supported by the implementation.