🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Assignment Type Conversion
What really happens when you store a double in an int, a 12-bit ADC reading in a byte, or -1 in an unsigned variable. Promotion, demotion and silent data loss explained with programs you can run. Part of the free C programming course.
Type conversion in assignment is the second family of implicit conversions in C, and it causes more real bugs than the expression rules you met in the previous lesson. Whenever you store a value into a variable of a different type, the compiler converts the value to match the variable. Sometimes that is harmless. Sometimes it quietly throws data away. This lesson of the free C programming course shows you exactly where the line is, with outputs from a real compiler.
If you plan to write firmware, treat this topic as essential. In embedded C programming you constantly squeeze wide values (timer counts, ADC samples, sensor words) into narrow registers and variables. Knowing what the compiler does at that moment separates code that works from code that merely compiles. Like every lesson in this free C tutorial, all programs build with plain GCC.
What You Will Learn
- The single rule behind type conversion in assignment: the right side is converted to the type of the left side
- The difference between promotion (safe widening) and demotion (possible data loss)
- Five concrete ways a demotion can damage a value, each demonstrated with output
- How to read GCC conversion warnings and what they are telling you
- How to scale a 12-bit ADC value into 8 bits correctly instead of by accident
Prerequisites
- The previous lesson on implicit type conversion in expressions
- Knowledge of C data types, their sizes, and the idea of a rank ladder
- GCC on a Linux terminal
The Rule for Type Conversion in Assignment
The rule fits in one sentence. In an assignment, the value of the right-hand expression is converted to the type of the left-hand variable, no matter what the ranks are. If the right side has a lower rank than the variable, the value is promoted, which is normally safe. If the right side has a higher rank, the value is demoted, and the conversion may change it.
This is different from the expression rules, where the compiler balances two operands towards the bigger type. Here the destination has the final say. The same behaviour applies when you initialise a variable, pass an argument to a function with a prototype, or return a value from a function, because C treats those like assignments.
Conversion flow during assignment
Promotion and Demotion in Action
Start with a program that shows the everyday cases. It stores a temperature reading, a negative constant and two character values into variables of other types. Save it as assign_basic.c.
#include <stdio.h>
int main(void)
{
double reading = 36.987;
int whole = reading;
int neg = -7.9;
float narrow = reading;
char letter = 66;
int code = 'z';
double widened = whole;
printf("whole = %d\n", whole);
printf("neg = %d\n", neg);
printf("narrow = %.6f\n", narrow);
printf("letter = %c\n", letter);
printf("code = %d\n", code);
printf("widened = %.2f\n", widened);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o assign_basic assign_basic.c
$ ./assign_basic
whole = 36
neg = -7
narrow = 36.987000
letter = B
code = 122
widened = 36.00
Go through the output line by line:
whole = 36: the double36.987was demoted toint. The fraction is simply cut off. There is no rounding.neg = -7: truncation goes towards zero, so-7.9becomes-7, not-8.narrow = 36.987000: a double demoted to float is rounded to the nearest float. It still looks right at six digits, but fewer digits are reliable.letter = B: the integer 66 fits acharand is the ASCII code for B. A char is just a small integer.code = 122: the character constant'z'is promoted toint.widened = 36.00: an int promoted to double is exact, but the fractional digits of the original are gone for good. Promotion cannot bring back information that an earlier demotion discarded.
Now see what a stricter compiler thinks of this code. The -Wconversion family of warnings flags the risky lines:
$ gcc -std=c11 -Wconversion -c assign_basic.c
assign_basic.c:6:22: warning: conversion from 'double' to 'int' may change value [-Wfloat-conversion]
assign_basic.c:7:22: warning: conversion from 'double' to 'int' changes value
from '-7.9000000000000004e+0' to '-7' [-Wfloat-conversion]
assign_basic.c:8:22: warning: conversion from 'double' to 'float' may change value [-Wfloat-conversion]
Five Ways Type Conversion in Assignment Loses Data
| Conversion | What happens | Defined by the standard? |
|---|---|---|
| Wider integer to narrower unsigned | Upper bits dropped (value taken modulo 2N) | Yes, always defined |
| Wider integer to narrower signed | Value changes if it does not fit | Implementation-defined (GCC wraps) |
| Floating type to integer | Fraction truncated towards zero | Defined only if the result fits; otherwise undefined behaviour |
| Double to float | Rounded to nearest float; huge values can overflow | Defined when in range |
| Signed to unsigned | Negative values wrap to large positive values | Yes, modulo arithmetic |
| Integer to float | Large integers lose low digits (24-bit mantissa) | Rounded to nearest representable |
The next program triggers four of these on purpose. Save it as assign_loss.c.
#include <stdio.h>
#include <stdint.h>
int main(void)
{
int big = 300;
uint8_t u8 = big;
int neg = -1;
unsigned u = neg;
uint8_t raw = 200;
int8_t s8 = raw;
int n = 16777217;
float f = n;
double d = 0.1;
float fl = d;
printf("300 into uint8_t = %u\n", u8);
printf("-1 into unsigned = %u\n", u);
printf("200 into int8_t = %d\n", s8);
printf("%d into float = %.1f\n", n, f);
printf("0.1 as double = %.10f\n", d);
printf("0.1 as float = %.10f\n", (double)fl);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o assign_loss assign_loss.c
$ ./assign_loss
300 into uint8_t = 44
-1 into unsigned = 4294967295
200 into int8_t = -56
16777217 into float = 16777216.0
0.1 as double = 0.1000000000
0.1 as float = 0.1000000015
What each line shows:
- 300 into uint8_t gives 44. In hexadecimal, 300 is
0x012C. A byte keeps only the low eight bits,0x2C, which is 44. - -1 into unsigned gives 4294967295. All 32 bits of the two’s complement pattern are set, and the unsigned interpretation reads them as a huge number.
- 200 into int8_t gives -56. The bit pattern
0xC8is reinterpreted as a signed byte. The standard calls this implementation-defined, and GCC wraps around as shown. - 16777217 into float gives 16777216.0. A float has a 24-bit mantissa, so it cannot represent every integer above 224 (16777216). The value 16777217 is rounded to the nearest representable neighbour.
- 0.1 as float is 0.1000000015. Converting back to double does not restore the original. The float is a slightly different number.
Why 300 becomes 44 in a uint8_t
The compiler was not silent about any of this. With -Wconversion and -Wsign-conversion GCC reports every risky line:
$ gcc -std=c11 -Wconversion -Wsign-conversion -c assign_loss.c
assign_loss.c:7:20: warning: conversion from 'int' to 'uint8_t' {aka 'unsigned char'} may change value
assign_loss.c:9:20: warning: conversion to 'unsigned int' from 'int' may change the sign of the result
assign_loss.c:11:20: warning: conversion to 'int8_t' from 'uint8_t' may change the sign of the result
assign_loss.c:13:20: warning: conversion from 'int' to 'float' may change value
assign_loss.c:15:20: warning: conversion from 'double' to 'float' may change value
Out-of-range float to int is undefined
Truncation of a float into an int is fine only when the truncated value fits in the destination type. Storing 1e20 into a 32-bit int is undefined behaviour, not just a wrong number. In firmware, clamp the value before you convert it.
Scaling an ADC Reading: Convert on Purpose
Here is the classic embedded use. A 12-bit ADC returns values from 0 to 4095. You want an 8-bit value for a display. Assigning the 12-bit value to a byte keeps the wrong bits. Shifting first keeps the most significant ones.
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint16_t adc = 1000;
uint8_t wrong = adc;
uint8_t right = adc >> 4;
printf("12-bit ADC value = %u\n", adc);
printf("plain assignment = %u\n", wrong);
printf("scaled with >> 4 = %u\n", right);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o adc_scale adc_scale.c
$ ./adc_scale
12-bit ADC value = 1000
plain assignment = 232
scaled with >> 4 = 62
The plain assignment gave 232, which is just the low byte of 1000 (0x3E8 keeps 0xE8). The correct scaled value is 62, which is 1000 >> 4. A reading of 1000 out of 4095 is about 24 percent of full scale, and 62 out of 255 is also about 24 percent. The wrongly assigned 232 would show roughly 91 percent. The code compiles either way, which is exactly why this bug survives until testing.
Real-World Uses of Type Conversion in Assignment
- Sensor drivers: raw 16-bit register reads stored into
int8_toruint8_tfields after scaling. - PWM and DAC output: a computed duty cycle in
floatorintis stored into a narrow timer compare register. - Return values: a function returning
intthat is assigned to auint8_tstatus variable. - Logging: storing
doublemeasurements infloatto halve memory use on small devices.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
| Assigning a wide counter to a byte | Values wrap around unexpectedly | Use a wide enough type, or clamp and scale before assigning |
| Expecting rounding when storing a float in an int | Result is always smaller than expected | Use lroundf() from math.h for rounding |
| Storing a negative number in an unsigned type | Huge positive number | Use a signed type, or check the sign first |
Assuming float holds any int exactly | Off-by-one errors above 16 million | Use double or keep the value as an integer |
Ignoring -Wconversion output | Bugs found late in testing | Fix each warning, or add an explicit, commented cast |
Best Practices for Type Conversion in Assignment
- Match variable types to the data they hold. Do not use
intout of habit when the data is a byte. - Range-check before demoting:
if (v > 255) v = 255;is better than letting the value wrap. - Write float constants with an
fsuffix when the variable is afloat. This avoids a double-to-float conversion hidden in the assignment. - Enable
-Wconversionin your build and fix every hit, or silence a hit deliberately with a cast so the next reader knows it was intended.
Performance: on a Cortex-M4F the FPU handles single precision in hardware, but double precision is done in software and can be many times slower, so unnecessary double-to-float conversions in a hot loop cost real time. Security: an attacker-controlled length that is demoted to a smaller type can pass a bounds check and still overflow a buffer, so check the range before narrowing.
Summary and Key Takeaways
- In an assignment the right side is converted to the type of the left variable.
- Promotion is normally safe. Demotion can drop bits, truncate fractions, round or change the sign.
- Unsigned narrowing is well defined. Signed narrowing is implementation-defined. Out-of-range float to int is undefined.
- Widening later never restores information that was lost earlier.
- Use
-Wconversion, clamp or scale deliberately, and choose variable types to match the data.
Conclusion
Type conversion in assignment follows a simple rule, but its consequences fill the bug trackers of embedded projects. You now know what each narrowing does to a value, how to see it in compiler output, and how to scale an ADC value properly. Next in this free embedded C course you will take control of conversions yourself with the cast operator.
Interview Questions on Assignment Conversion
What value does uint8_t x = 300; store?
44. Only the low eight bits of 300 (0x2C) are kept.
What does int n = -7.9; store?
-7. A floating value is truncated towards zero, not rounded.
Can an int always be stored in a float without loss?
No. A 32-bit float has a 24-bit mantissa, so integers above 16777216 may be rounded.
Frequently Asked Questions
What is type conversion in assignment in C?
When the two sides of an assignment have different types, the right-hand value is converted to the type of the left-hand variable before it is stored.
Does C round when I assign a float to an int?
No. The fractional part is truncated towards zero. Use lround or lroundf if you want rounding.
What happens when I assign a large int to a char?
For unsigned char the value wraps modulo 256. For signed char the result is implementation-defined, and GCC wraps it.
Why does a negative number become huge when stored in an unsigned variable?
The bit pattern of the negative number is read as an unsigned value, so -1 becomes the largest value the type can hold.
How do I find risky conversions in my code?
Compile with -Wconversion -Wsign-conversion (and -Wfloat-conversion) and read every warning.
Is this free embedded C course enough to start firmware work?
It covers the language fundamentals that firmware depends on, with a focus on the behaviours that cause real bugs 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