Integer type conversion occurs when a value of one integer type is converted to another integer type. C performs these conversions implicitly in several situations, such as assignments and expressions.
#include <stdio.h>
int main()
{
char a = 10;
int b = 20;
int result = a + b;
printf("a = %d\n", a);
printf("b = %d\n", b);
printf("result = %d\n", result);
return 0;
}
Example Output #
a = 10
b = 20
result = 30
Explanation #
Before the addition is performed, a undergoes integer promotion:
a + b
Since a is a char, it is promoted to int when int can represent all values of the original type. The addition is therefore performed using int operands.
The result of the addition is an int, which is stored in:
int result
Common Integer Conversions #
| Conversion | Example | Resulting type |
|---|---|---|
char → int |
char + int |
int |
short → int |
short + int |
int |
char → unsigned int |
assignment/conversion | unsigned int |
int → long |
long x = int_value |
long |
int → short |
short x = int_value |
short |
int → char |
char x = int_value |
char |
Integer Promotion #
Integer types with rank lower than int, such as char and short, are subject to integer promotions when used in most expressions.
char a = 10;
char b = 20;
int result = a + b;
Both a and b are promoted before the addition, so the operation is performed using int.
Conversion During Assignment #
Conversion also occurs when an integer value is assigned to an object of a different integer type.
int number = 100;
short value = number;
The value of number is converted to short before being stored in value. If the destination type cannot represent the value, the resulting value follows the rules for conversion to that integer type.
Integer conversion rules become more involved when signed and unsigned types are combined. Those cases are covered further in the type-conversion section.