🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Implicit Type Conversion
How the compiler silently converts types inside expressions: integer promotion, the usual arithmetic conversions, and the traps that break embedded C code. Part of the free C programming course, chapter Operators and Expressions.
Implicit type conversion in C happens every time you mix different data types in a single expression. You write c + 1.5f, the compiler quietly turns c into a float, does the arithmetic, and hands back a result type you never asked for. In this lesson of our free C programming course you will learn exactly which rules the compiler follows, why they exist, and how they bite in embedded C programming when you work with uint8_t registers and sensor readings.
Rules like these look dry on paper, so we will not memorise them blindly. You will run a small program that makes the compiler report the result type of each expression, and then break things on purpose with two classic traps. Everything builds with GCC on any Linux machine, so this free C tutorial needs no hardware at all.
What You Will Learn
- The two families of implicit type conversion in C: conversions inside expressions and conversions during assignment
- How integer promotion (the automatic unary conversion) widens
charandshorttoint - The usual arithmetic conversions (the automatic binary conversion) that balance two operands
- A simple type rank ladder you can use to predict the result type of any mixed expression
- Why comparing a signed value with an unsigned value gives wrong answers
- How promotion changes the meaning of
~and shifts onuint8_tregister values
Prerequisites
- Basic C data types and their sizes, from the Elements of C chapter of this free embedded C course
- The arithmetic and logical operators covered earlier in this chapter
- GCC installed (
sudo apt install build-essentialon Ubuntu) and a terminal
Types of Type Conversion in C
C converts types in two situations. The vocabulary matters because exams and interviewers use it, so keep it straight. An implicit conversion is done by the compiler, following rules fixed by the language standard. An explicit conversion is one you ask for yourself with the cast operator, which gets its own lesson later in this chapter.
Implicit conversions split again. Some happen inside an expression (the compiler balances the operands before it calculates). Others happen when a value is stored into a variable of a different type, which is covered in the next lesson. Inside an expression there are two kinds. A unary conversion fixes up one small operand on its own. A binary conversion makes two operands agree on a common type. The C standard calls these integer promotions and the usual arithmetic conversions. Many textbooks, including the book this chapter is based on, call them automatic unary conversion and automatic binary conversion. They are the same ideas under different names.
Where implicit type conversion in C fits
Integer Promotion: The Unary Conversion
Before an arithmetic operator looks at its operands, any operand narrower than int is converted to int. This covers char, signed char, unsigned char, short, unsigned short and _Bool. If int cannot hold every value of the original type (possible on exotic targets where short and int are both 16 bits), the operand becomes unsigned int instead. On a desktop or a 32-bit microcontroller you can simply remember: smaller than int becomes int.
The reason is hardware. A Cortex-M add instruction works on 32-bit registers, so computing with 8-bit values means widening them anyway. C builds that fact into the language.
Two details trip up students. First, promotion converts the value used in the expression. The variable itself stays a char. Second, the same promotion applies to operands of ~ and of the shift operators, which matters a lot in register code (see below). One more point from older books: some early compilers converted every float operand to double before any arithmetic. Modern C does not require that. float + float stays float on typical targets. The only place a float is widened to double automatically is when you pass it to a variadic function such as printf.
Usual Arithmetic Conversions: The Binary Conversion
When the two operands of a binary operator have different types, the compiler applies the usual arithmetic conversions. Floating types win first. Integer types are handled afterwards, always after integer promotion has been applied to both sides. Read the rules top to bottom and stop at the first one that matches.
| Step | Condition | Both operands become | Example |
|---|---|---|---|
| 1 | One operand is long double | long double | 2.0 + 1.0L |
| 2 | Else, one operand is double | double | f + 2.0 |
| 3 | Else, one operand is float | float | c + f |
| 4 | Else, apply integer promotion to both | then continue below | c + c |
| 5 | Same type now | that type, done | int + int |
| 6 | Both signed, or both unsigned | the type of higher rank | c + 2L gives long |
| 7 | Unsigned operand has rank equal or higher than the signed one | the unsigned type | 1u + 1 gives unsigned int |
| 8 | Else, signed type can represent every value of the unsigned type | the signed type | 1u + 2L on 64-bit Linux gives long |
| 9 | Else | the unsigned version of the signed type | 1u + 2L on a 32-bit target gives unsigned long |
If you ignore the unsigned cases, the whole thing collapses into a simple picture. Give each type a rank. Whenever two operands differ, the lower-ranked one is promoted to the higher-ranked type. Floating types sit above all integer types.
Simplified type rank ladder (promotion goes upward)
Check It Yourself: Which Type Does the Compiler Pick?
Instead of trusting a table, ask the compiler. The program below uses the C11 _Generic keyword to print the type of an expression. The TYPE_NAME macro picks a string depending on the type of its argument, and sizeof shows how wide the result is. Save it as type_rank.c.
#include <stdio.h>
#define TYPE_NAME(x) _Generic((x), \
char: "char", signed char: "signed char", unsigned char: "unsigned char", \
short: "short", unsigned short: "unsigned short", \
int: "int", unsigned int: "unsigned int", \
long: "long", unsigned long: "unsigned long", \
long long: "long long", unsigned long long: "unsigned long long", \
float: "float", double: "double", long double: "long double")
int main(void)
{
char c = 'A';
short s = 10;
float f = 1.5f;
printf("c + c -> %s (%zu bytes)\n", TYPE_NAME(c + c), sizeof(c + c));
printf("s * s -> %s\n", TYPE_NAME(s * s));
printf("c + f -> %s\n", TYPE_NAME(c + f));
printf("f + f -> %s\n", TYPE_NAME(f + f));
printf("f + 2.0 -> %s\n", TYPE_NAME(f + 2.0));
printf("2.0 + 1.0L -> %s\n", TYPE_NAME(2.0 + 1.0L));
printf("c + 2L -> %s\n", TYPE_NAME(c + 2L));
printf("1u + 1 -> %s\n", TYPE_NAME(1u + 1));
printf("1u + 2L -> %s\n", TYPE_NAME(1u + 2L));
printf("1ul + 2L -> %s\n", TYPE_NAME(1ul + 2L));
return 0;
}
Build and run it:
$ gcc -std=c11 -Wall -Wextra -o type_rank type_rank.c
$ ./type_rank
c + c -> int (4 bytes)
s * s -> int
c + f -> float
f + f -> float
f + 2.0 -> double
2.0 + 1.0L -> long double
c + 2L -> long
1u + 1 -> unsigned int
1u + 2L -> long
1ul + 2L -> unsigned long
Read the output against the rules. c + c is int because both char operands were promoted (step 4), so a sum of two chars occupies 4 bytes. c + f is float (step 3). f + 2.0 is double because the literal 2.0 is a double (step 2). c + 2L becomes long (step 6).
Result types depend on the target
The last two lines are the interesting ones. On 64-bit Linux, long is 64 bits wide and can hold every unsigned int, so 1u + 2L is long (step 8). On a 32-bit microcontroller such as a Cortex-M, long is only 32 bits, so the same expression is unsigned long (step 9). The same source code can compute with different types on different chips. This is why embedded programmers prefer fixed-width types from stdint.h.
The Signed and Unsigned Trap
Rule 7 hides the most common bug in this whole topic. When a signed int meets an unsigned int, they have equal rank, so the signed operand is converted to unsigned. A negative number does not survive that trip.
#include <stdio.h>
int main(void)
{
int a = -1;
unsigned int b = 1;
if (a < b)
puts("-1 < 1u : true");
else
puts("-1 < 1u : false (surprise!)");
printf("a seen as unsigned = %u\n", (unsigned int)a);
return 0;
}
Compile with warnings turned on, then run it:
$ gcc -std=c11 -Wall -Wextra -o sign_trap sign_trap.c
sign_trap.c: In function 'main':
sign_trap.c:8:11: warning: comparison of integer expressions of different
signedness: 'int' and 'unsigned int' [-Wsign-compare]
$ ./sign_trap
-1 < 1u : false (surprise!)
a seen as unsigned = 4294967295
The value -1 became 4294967295 before the comparison, so the test -1 < 1u was false. GCC even warned you, which is why you should always build with -Wall -Wextra. The fix is to keep the two operands the same signedness, or to check the sign explicitly: if (a < 0 || (unsigned int)a < b).
Watch out for size_t loops
size_t is unsigned. A loop such as for (size_t i = n - 1; i >= 0; i--) never ends, because an unsigned value is always greater than or equal to zero. When i reaches 0 and is decremented, it wraps to a huge number. Use a signed index or restructure the loop.
Integer Promotion Surprise in Embedded Register Code
Here is a bug that catches working engineers. You hold a mask in a uint8_t and want to compare its complement with a constant. Integer promotion widens the byte to int before the ~ operator runs, so the complement has 32 bits, not 8.
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint8_t mask = 0xF0;
uint8_t inv = (uint8_t)~mask;
printf("~mask as int = 0x%08X\n", (unsigned int)~mask);
printf("~mask == 0x0F : %s\n", (~mask == 0x0F) ? "true" : "false");
printf("inv == 0x0F : %s\n", (inv == 0x0F) ? "true" : "false");
printf("(uint8_t)~mask == 0x0F : %s\n",
((uint8_t)~mask == 0x0F) ? "true" : "false");
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o mask_promo mask_promo.c
$ ./mask_promo
~mask as int = 0xFFFFFF0F
~mask == 0x0F : false
inv == 0x0F : true
(uint8_t)~mask == 0x0F : true
The promoted ~mask is 0xFFFFFF0F, which is not 0x0F, so the first comparison is false. Storing the result back into a uint8_t (or casting it) throws away the upper bits and the comparison becomes true. GCC reports the first line with -Wsign-compare as well.
Real-World Uses of Implicit Type Conversion in C
- ADC averaging: adding several
uint16_tsamples into auint32_taccumulator so the sum does not overflow. The additions rely on promotion. - Protocol parsing: bytes from a UART or CAN frame are
uint8_t. Every shift or mask on them is silently done inint. - Timer arithmetic: comparing tick counters mixes
uint32_twithintdelays, and the signed side is converted to unsigned. - Formatted output:
printfreceivesfloatarguments asdouble, and small integers asint, because of default argument promotion.
Common Mistakes in Implicit Type Conversion in C
| Mistake | Symptom | Fix |
|---|---|---|
Comparing int with unsigned | Negative numbers compare as huge positives | Use one signedness, or test a < 0 first. Enable -Wsign-compare. |
Using ~ on a uint8_t in a comparison | Condition is always false | Cast the result back: (uint8_t)~mask |
Assuming char + char is a char | Overflow does not wrap at 255 inside the expression | Remember the result is int. Wrapping only happens on assignment. |
Expecting float arithmetic to use double | Confusion about precision | Check the literal suffix: 2.0 is double, 2.0f is float. |
| Looping down with an unsigned index | Infinite loop | Use a signed counter, or loop with i-- > 0. |
Best Practices for Implicit Type Conversion in C
- Compile with
-Wall -Wextra -Wsign-compare -Wconversionand treat the warnings as bugs. - Use the fixed-width types
uint8_t,int32_tand friends so the result type does not change between chips. - Keep signed and unsigned values apart. When you must mix them, convert one side with an explicit cast that you can justify in a comment.
- Use
fsuffixes on float constants (2.0f) so a small MCU with a single-precision FPU does not fall back to slow double arithmetic.
Performance: on a 32-bit core, promoting a byte to int costs nothing. On an 8-bit AVR, where int is 16 bits wide, every promotion adds instructions, and tight loops can benefit from carefully chosen types. Security: signed-to-unsigned conversion errors in length checks are a classic route to buffer overflows (CERT rule INT31-C and CWE-195 describe the pattern), so validate lengths before converting.
Summary and Key Takeaways
- Implicit conversions are done by the compiler. Explicit conversions are casts written by you.
- Operands smaller than
intare promoted tointbefore arithmetic, shifts and~. - For two different types, the lower rank is converted to the higher rank, and floating types outrank integers.
- When signed meets unsigned of equal rank, the signed value is converted to unsigned.
- Result types such as
1u + 2Ldepend on the target. Fixed-width types remove the guesswork.
Conclusion
Implicit type conversion in C is not magic, it is a short list of rules applied in a fixed order. Once you know them, mixed expressions stop being surprising. You can predict the result type, spot the signed and unsigned trap before it ships, and explain why a uint8_t mask behaves strangely after ~. In the next lesson of this free embedded C course you will see the second family, where a value is converted because of the variable it is assigned to.
Interview Questions on Implicit Type Conversion
What is the type of c1 + c2 if both are char?
int. Both operands undergo integer promotion before the addition.
Why is -1 < 1u false in C?
The signed -1 is converted to unsigned int (4294967295) because the unsigned operand has equal rank, so the comparison is between 4294967295 and 1.
Is ~(uint8_t)0xF0 == 0x0F true?
No. The byte is promoted to int first, so the complement is 0xFFFFFF0F.
Frequently Asked Questions
What is implicit type conversion in C?
It is a conversion the compiler performs automatically when operands of different types appear in an expression or an assignment. The rules are defined by the C standard, and you do not write any code to trigger them.
What is the difference between implicit and explicit type conversion?
Implicit conversion is automatic and rule-driven. Explicit conversion, called type casting, is requested by the programmer with the cast operator, for example (float)x.
What is integer promotion in C?
Integer promotion converts operands of type char, short and _Bool to int (or unsigned int when int cannot hold all values) before arithmetic is performed.
Does C convert float to double automatically?
Not in ordinary arithmetic. float + float stays float on typical targets. A float is widened to double when passed to a variadic function such as printf.
Why do I get a sign-compare warning?
GCC warns because comparing signed and unsigned values converts the signed one to unsigned, which can change a negative number into a very large positive number.
Is this free C programming course suitable for embedded beginners?
Yes. The lessons start from the basics, use programs you can run on a normal Linux PC, and point out where each rule matters on microcontrollers.
Keep Going With the Free C Programming Course
Every lesson is free, written for students, and built around programs you can compile and run on any Linux machine. Move on to the next lecture or return to the course index to pick your own path.

2 Comments