sizeof and Type Casting Examples: Promotion, Registers and Truncation-Free Embedded C Tutorial Online

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

MODULE 3 · LESSON 3.3 · EXAMPLES

sizeof and Type Casting Examples: Promotion, Registers and Truncation

Eleven worked examples with verified output: a sizeof table, array and string sizes, promotion gallery, signed/unsigned traps, simulated register access through casts, byte lanes, truncation and saturating conversions.

11
Worked Examples
Beginner → Intermediate
Level
Real output
Compiled and run

sizeof and Type Casting Examples: What This Page Covers

These sizeof and type casting examples put Lesson 3.3 into practice. Each program was compiled and run. The register examples are simulated on the PC by pointing the same casts at an ordinary array, so you can see exactly what the casts do before using them on the STM32F407.

#ExampleSkill
1A complete sizeof table programSizes
2Array length, strings and structure arrayssizeof on objects
3Surprising sizeof resultsLiterals and expressions
4Integer promotion galleryImplicit conversion
5Signed and unsigned comparison trapsArithmetic conversions
6Casting an address to a register (simulated RCC and GPIOD)Memory-mapped I/O
7Pointer width decides access width (byte lanes)Pointer casts
8Truncation examples: ADC, PWM, temperatureNarrowing
9Float to integer: rounding and range checksSafe casting
10Saturating cast helpersDefensive code
11Mini exercisesSelf-test

Example 1: A Complete sizeof Table Program

The first of the sizeof and type casting examples is a reusable report. Problem: Print the size of every common type with one reusable macro. The #t operator turns the macro argument into a string, so each line is labelled automatically.

sizeof_table.c
#include <stdio.h> #include <stdint.h> #include <stddef.h> #define SHOW(t) printf(“%-14s %2zu bytes %3zu bits\n”, #t, sizeof(t), sizeof(t) * 8) int main(void) { SHOW(char); SHOW(short); SHOW(int); SHOW(long); SHOW(long long); SHOW(float); SHOW(double); SHOW(void *); SHOW(size_t); SHOW(ptrdiff_t); SHOW(uint8_t); SHOW(uint16_t); SHOW(uint32_t); SHOW(uint64_t); SHOW(int8_t); SHOW(int16_t); SHOW(int32_t); SHOW(int64_t); return 0; }
Output on a 64-bit Linux PC
char 1 bytes 8 bits short 2 bytes 16 bits int 4 bytes 32 bits long 8 bytes 64 bits long long 8 bytes 64 bits float 4 bytes 32 bits double 8 bytes 64 bits void * 8 bytes 64 bits size_t 8 bytes 64 bits ptrdiff_t 8 bytes 64 bits uint8_t 1 bytes 8 bits uint16_t 2 bytes 16 bits uint32_t 4 bytes 32 bits uint64_t 8 bytes 64 bits int8_t 1 bytes 8 bits int16_t 2 bytes 16 bits int32_t 4 bytes 32 bits int64_t 8 bytes 64 bits
TypeThis PCSTM32F407 (arm-none-eabi-gcc)
long84
void *84
size_t84
ptrdiff_t84
all other rowssamesame
How to get the real ARM numbers: Compile the same file with arm-none-eabi-gcc -c and use _Static_assert(sizeof(long) == 4, "..."), or print the sizes over the UART in a test build. Never trust a PC run for target sizes.

Example 2: Array Length, Strings and Structure Arrays

Problem: Find the number of elements in an array, the size of a string and the size of an array of structures without hard-coding any numbers.

sizeof_objects.c
#include <stdio.h> #include <stdint.h> #include <string.h> #define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0])) typedef struct { uint8_t id; uint16_t value; } Sample; int main(void) { uint16_t adc[16]; Sample log[5]; char name[] = “STM32F407”; char buf[32] = “STM32”; const char *ptr = “STM32F407”; printf(“adc : %zu bytes, %zu elements\n”, sizeof(adc), ARRAY_LEN(adc)); printf(“log : %zu bytes, %zu elements, %zu bytes each\n”, sizeof(log), ARRAY_LEN(log), sizeof(log[0])); printf(“name: sizeof = %zu, strlen = %zu\n”, sizeof(name), strlen(name)); printf(“buf : sizeof = %zu, strlen = %zu\n”, sizeof(buf), strlen(buf)); printf(“ptr : sizeof = %zu, strlen = %zu (sizeof a pointer, not the text)\n”, sizeof(ptr), strlen(ptr)); memset(adc, 0, sizeof(adc)); /* safe: tracks the array size */ printf(“cleared %zu bytes of adc\n”, sizeof(adc)); return 0; }
Output (verified by compiling and running)
adc : 32 bytes, 16 elements log : 20 bytes, 5 elements, 4 bytes each name: sizeof = 10, strlen = 9 buf : sizeof = 32, strlen = 5 ptr : sizeof = 8, strlen = 9 (sizeof a pointer, not the text) cleared 32 bytes of adc
sizeof versus strlen for char name[] = “STM32F407”
S
T
M
3
2
F
4
0
7
\0
strlen counts 9 characters; sizeof counts 10 bytes because the terminating zero is stored too
Reusable macro: ARRAY_LEN(a) only works on a real array in the same scope. On a pointer it silently divides the pointer size by the element size and returns a wrong number.

Example 3: Surprising sizeof Results

The next sizeof and type casting examples are quiz-like: Problem: Predict each result before running: the types of literals and of promoted expressions are not always what they look like.

sizeof_surprises.c
#include <stdio.h> #include <stdint.h> int main(void) { printf(“sizeof(‘A’) = %zu (a character constant is an int in C)\n”, sizeof(‘A’)); char c = ‘A’; printf(“sizeof(c) = %zu\n”, sizeof(c)); printf(“sizeof(1.5) = %zu (double)\n”, sizeof(1.5)); printf(“sizeof(1.5f) = %zu (float)\n”, sizeof(1.5f)); printf(“sizeof(1) = %zu\n”, sizeof(1)); printf(“sizeof(1L) = %zu (4 on ARM)\n”, sizeof(1L)); printf(“sizeof(1LL) = %zu\n”, sizeof(1LL)); printf(“sizeof(5 > 3) = %zu (comparison yields int)\n”, sizeof(5 > 3)); printf(“sizeof(c + c) = %zu (promoted to int)\n”, sizeof(c + c)); printf(“sizeof(sizeof(int)) = %zu (size_t; 4 on ARM)\n”, sizeof(sizeof(int))); uint8_t u8 = 1; printf(“sizeof(u8) = %zu, sizeof(u8 << 1) = %zu, sizeof(~u8) = %zu\n”, sizeof(u8), sizeof(u8 << 1), sizeof(~u8)); return 0; }
Output (verified by compiling and running)
sizeof(‘A’) = 4 (a character constant is an int in C) sizeof(c) = 1 sizeof(1.5) = 8 (double) sizeof(1.5f) = 4 (float) sizeof(1) = 4 sizeof(1L) = 8 (4 on ARM) sizeof(1LL) = 8 sizeof(5 > 3) = 4 (comparison yields int) sizeof(c + c) = 4 (promoted to int) sizeof(sizeof(int)) = 8 (size_t; 4 on ARM) sizeof(u8) = 1, sizeof(u8 << 1) = 4, sizeof(~u8) = 4
ExpressionTypeWhy
'A'intIn C (not C++) character constants have type int
1.5doubleFloating literals default to double
5 > 3intRelational operators yield int 0 or 1
c + cintInteger promotion
~u8intUnary operators promote too

Example 4: Integer Promotion Gallery

Problem: What do expressions of narrow types really produce? Each line below is computed in int; the casts show what you get if you store it back into the narrow type.

promotion_gallery.c
#include <stdio.h> #include <stdint.h> int main(void) { uint8_t a = 200, b = 100, small = 5, big = 10; int8_t n = –5; uint16_t w = 60000; printf(“a + b = %d\n”, a + b); printf(“a * b = %d\n”, a * b); printf(“small – big = %d\n”, small – big); printf(“(uint8_t)(small – big) = %u\n”, (uint8_t)(small – big)); printf(“~small = %d\n”, ~small); printf(“(uint8_t)~small = %u\n”, (uint8_t)~small); printf(“n * 100 = %d\n”, n * 100); printf(“w + w = %d\n”, w + w); printf(“(uint16_t)(w + w) = %u\n”, (uint16_t)(w + w)); printf(“a << 4 = %d\n”, a << 4); printf(“(uint8_t)(a << 4) = %u\n”, (uint8_t)(a << 4)); printf(“a / 3 * 3 and a %% 3 = %d %d\n”, a / 3 * 3, a % 3); return 0; }
Output (verified by compiling and running)
a + b = 300 a * b = 20000 small – big = -5 (uint8_t)(small – big) = 251 ~small = -6 (uint8_t)~small = 250 n * 100 = -500 w + w = 120000 (uint16_t)(w + w) = 54464 a << 4 = 3200 (uint8_t)(a << 4) = 128 a / 3 * 3 and a % 3 = 198 2
Computed wide, stored narrow
operands
uint8_t, uint8_t
→
promoted
int (32 bits)
→
operation in
32-bit registers
→
result
int (or cast back)
Practical rule: Do arithmetic freely in int, then narrow once at the end with an explicit cast so the intent is visible.

Example 5: Signed and Unsigned Comparison Traps

This one of the sizeof and type casting examples explains many “impossible” bugs. Problem: Why do comparisons between signed and unsigned values sometimes give the “wrong” answer? The rule: when ranks are equal, the signed operand is converted to unsigned.

signed_unsigned.c
#include <stdio.h> #include <stdint.h> int main(void) { int i = –1; unsigned u = 1; int32_t s32 = –5; uint32_t u32 = 3; printf(“i < u : %d (i converted to unsigned)\n”, i < u); printf(“(unsigned)i < u : %d\n”, (unsigned)i < u); printf(“s32 < u32 : %d\n”, s32 < u32); printf(“s32 + u32 (as unsigned) : %u\n”, (unsigned)(s32 + u32)); printf(“(int32_t)(s32 + u32) : %d\n”, (int32_t)(s32 + u32)); /* The countdown-loop bug with an unsigned index */ unsigned n = 3, count = 0; for (unsigned k = n; k != (unsigned)-1; k–) { count++; } printf(“iterations with ‘k != (unsigned)-1’ : %u (0,1,2,3)\n”, count); printf(“safe pattern: for (k = n; k– > 0; ) visits n-1 .. 0\n”); return 0; }
Output (verified by compiling and running)
i < u : 0 (i converted to unsigned) (unsigned)i < u : 0 s32 < u32 : 0 s32 + u32 (as unsigned) : 4294967294 (int32_t)(s32 + u32) : -2 iterations with ‘k != (unsigned)-1’ : 4 (0,1,2,3) safe pattern: for (k = n; k– > 0; ) visits n-1 .. 0
ComparisonTypesConverted toResult for −1 and 1
-1 < 1int, intinttrue
-1 < 1uint, unsignedunsigned (−1 → 4294967295)false
(int8_t)-1 < (uint8_t)1both promotedinttrue
(int32_t)-1 < (uint32_t)1int32_t, uint32_tuint32_tfalse
Compiler help: -Wsign-compare (in -Wextra) reports exactly these comparisons. Treat it as an error in firmware.

Example 6: Casting an Address to a Register (Simulated RCC and GPIOD)

The register case is the key of the sizeof and type casting examples for firmware. Problem: Enable the GPIOD clock in RCC and switch the green LED on PD12, using the macro style from the theory page. The program runs on a PC by placing the “peripherals” inside an array; on the board you would only replace the two base addresses.

register_sim.c
#include <stdio.h> #include <stdint.h> #include <inttypes.h> /* —- Simulated memory standing in for the peripheral address space —- */ static uint32_t sim_mem[128]; /* 512 bytes, 4-byte aligned */ #define SIM(off) ((uintptr_t)sim_mem + (off)) /* On the real STM32F407 these would be 0x40023800 (RCC) and 0x40020C00 (GPIOD) */ #define RCC_BASE SIM(0x000) #define GPIOD_BASE SIM(0x100) #define REG32(addr) (*(volatile uint32_t *)(addr)) #define RCC_AHB1ENR REG32(RCC_BASE + 0x30) #define GPIOD_MODER REG32(GPIOD_BASE + 0x00) #define GPIOD_ODR REG32(GPIOD_BASE + 0x14) int main(void) { printf(“RCC_AHB1ENR address offset = 0x%” PRIXPTR “\n”, RCC_BASE + 0x30 – SIM(0)); printf(“GPIOD_ODR address offset = 0x%” PRIXPTR “\n”, GPIOD_BASE + 0x14 – SIM(0)); RCC_AHB1ENR |= (1U << 3); /* enable GPIOD clock (bit 3) */ printf(“RCC_AHB1ENR = 0x%08” PRIX32 “\n”, RCC_AHB1ENR); GPIOD_MODER &= ~(3U << 24); /* PD12: clear mode bits */ GPIOD_MODER |= (1U << 24); /* PD12: output */ printf(“GPIOD_MODER = 0x%08” PRIX32 “\n”, GPIOD_MODER); GPIOD_ODR |= (1U << 12); /* LED on */ printf(“GPIOD_ODR on = 0x%08” PRIX32 “\n”, GPIOD_ODR); GPIOD_ODR &= ~(1U << 12); /* LED off */ printf(“GPIOD_ODR off= 0x%08” PRIX32 “\n”, GPIOD_ODR); return 0; }
Output (verified by compiling and running)
RCC_AHB1ENR address offset = 0x30 GPIOD_ODR address offset = 0x114 RCC_AHB1ENR = 0x00000008 GPIOD_MODER = 0x01000000 GPIOD_ODR on = 0x00001000 GPIOD_ODR off= 0x00000000
Same code, different base address
On the STM32F407
#define RCC_BASE    0x40023800UL
#define GPIOD_BASE 0x40020C00UL
In the PC simulation
#define RCC_BASE    SIM(0x000)
#define GPIOD_BASE SIM(0x100)
Why this is valuable: The logic of a driver (which bit, which register, what order) can be unit-tested on a PC by redirecting the base addresses, long before hardware is available.

Example 7: The Pointer Type Decides the Access Width

Problem: The same 4 bytes can be viewed as one 32-bit word, two 16-bit half-words or four bytes, simply by changing the pointer type in the cast. Watch how a narrow write changes only part of the word.

byte_lanes.c
#include <stdio.h> #include <stdint.h> #include <inttypes.h> int main(void) { static uint32_t reg; /* pretend this is GPIOD_ODR */ reg = 0; volatile uint32_t *w32 = &reg; volatile uint16_t *w16 = (volatile uint16_t *)&reg; volatile uint8_t *w8 = (volatile uint8_t *)&reg; *w32 = 0x11223344u; printf(“32-bit value : 0x%08” PRIX32 “\n”, *w32); printf(“byte 0 (lowest addr) : 0x%02X\n”, w8[0]); printf(“byte 1 : 0x%02X\n”, w8[1]); printf(“byte 2 : 0x%02X\n”, w8[2]); printf(“byte 3 : 0x%02X\n”, w8[3]); printf(“half-word 0 : 0x%04X\n”, w16[0]); printf(“half-word 1 : 0x%04X\n”, w16[1]); w8[1] = 0xF0; /* write only the second byte */ printf(“after w8[1] = 0xF0 : 0x%08” PRIX32 “\n”, *w32); w16[1] = 0xBEEF; /* write the upper half-word */ printf(“after w16[1] = 0xBEEF: 0x%08” PRIX32 “\n”, *w32); return 0; }
Output on a little-endian machine (the Cortex-M4 behaves identically)
32-bit value : 0x11223344 byte 0 (lowest addr) : 0x44 byte 1 : 0x33 byte 2 : 0x22 byte 3 : 0x11 half-word 0 : 0x3344 half-word 1 : 0x1122 after w8[1] = 0xF0 : 0x1122F044 after w16[1] = 0xBEEF: 0xBEEFF044
0x11223344 stored little-endian: the least significant byte has the lowest address
bytes in memory
0x20000000
44
0x20000001
33
0x20000002
22
0x20000003
11
w8[0] = 0x44
w8[1] = 0x33
w8[2] = 0x22
w8[3] = 0x11
On real hardware: Many peripheral registers only support full 32-bit accesses, or behave differently for narrow ones. Check the reference manual before using a byte or half-word pointer on a register; the default should always be the full register width.

Example 8: Truncation Examples: ADC, PWM and Temperature

Truncation is the most frequent defect in the sizeof and type casting examples below. Problem: Three realistic narrowing mistakes. Run them, then decide how you would prevent each.

truncation_cases.c
#include <stdio.h> #include <stdint.h> int main(void) { uint16_t adc = 3000; /* 12-bit reading: 0..4095 */ uint8_t lost = (uint8_t)adc; /* WRONG: keeps low 8 bits */ uint8_t scaled = (uint8_t)(adc >> 4); /* RIGHT: keep top 8 bits */ printf(“ADC 3000 -> low byte : %u (data destroyed)\n”, lost); printf(“ADC 3000 -> adc >> 4 : %u (0..255 scale)\n”, scaled); printf(“percent : %u %%\n”, (unsigned)((uint32_t)adc * 100u / 4095u)); uint16_t duty = 1200, period = 1000; uint8_t duty8 = (uint8_t)duty; printf(“duty 1200 as uint8_t : %u (period %u)\n”, duty8, period); int32_t temp_x10 = 1253; /* 125.3 degrees */ int8_t temp_c = (int8_t)(temp_x10 / 10); printf(“125.3 C as int8_t : %d (overflow: range is -128..127)\n”, temp_c); int32_t position = –70000; int16_t pos16 = (int16_t)position; printf(“-70000 as int16_t : %d\n”, pos16); return 0; }
Output (verified by compiling and running)
ADC 3000 -> low byte : 184 (data destroyed) ADC 3000 -> adc >> 4 : 187 (0..255 scale) percent : 73 % duty 1200 as uint8_t : 176 (period 1000) 125.3 C as int8_t : 125 (overflow: range is -128..127) -70000 as int16_t : -4464
CaseMistakeFix
12-bit ADC into uint8_tKeeps the low byte: 3000 becomes 184Shift right by 4 to scale, or keep uint16_t
PWM duty above period1200 becomes 176 and the duty looks validClamp to the period first
125.3 °C into int8_tValue 125 fits, but 130 would wrap negativeUse int16_t for the range −40..+150
−70000 into int16_tWraps to −4464Use int32_t or range-check

Example 9: Float to Integer: Truncation, Rounding and Conversion

Problem: A cast from float to an integer type truncates toward zero. How do you round instead, and how do you compute a DAC or ADC code from a voltage?

float_to_int.c
#include <stdio.h> #include <stdint.h> #include <math.h> static int32_t round_to_int(float x) { return (int32_t)(x >= 0.0f ? x + 0.5f : x – 0.5f); /* round half away from zero */ } int main(void) { float samples[] = { 2.4f, 2.5f, 2.6f, –2.4f, –2.5f, –2.6f }; printf(“%6s %8s %8s %8s\n”, “x”, “(int)x”, “round”, “floorf”); for (unsigned i = 0; i < sizeof samples / sizeof samples[0]; i++) printf(“%6.1f %8d %8d %8.0f\n”, samples[i], (int)samples[i], (int)round_to_int(samples[i]), floorf(samples[i])); float volts = 1.65f; /* 3.3 V reference, 12-bit */ uint16_t counts = (uint16_t)(volts / 3.3f * 4095.0f + 0.5f); printf(“1.65 V -> %u counts\n”, counts); return 0; }
Output (verified by compiling and running)
x (int)x round floorf 2.4 2 2 2 2.5 2 3 2 2.6 2 3 2 -2.4 -2 -2 -3 -2.5 -2 -3 -3 -2.6 -2 -3 -3 1.65 V -> 2048 counts

Casting 2.5f and -2.5f gives 2 and −2 (toward zero), while the rounding helper gives 3 and −3. floorf always goes down. Adding 0.5 before the cast is the usual idiom for non-negative values.

Range check: If the float is outside the range of the target integer type, the conversion is undefined behaviour. Clamp first (next example).

Example 10: Saturating Cast Helpers

Defensive casting closes the sizeof and type casting examples. Problem: Audio, motor control and PWM code should clip an out-of-range value to the nearest limit instead of wrapping around. Write small helper functions that perform the range check before the cast.

saturate.c
#include <stdio.h> #include <stdint.h> static uint8_t sat_u8(int32_t v) { return (uint8_t)(v < 0 ? 0 : (v > 255 ? 255 : v)); } static int16_t sat_i16(int32_t v) { return (int16_t)(v < INT16_MIN ? INT16_MIN : (v > INT16_MAX ? INT16_MAX : v)); } static uint16_t f_to_u16(float x) { if (!(x > 0.0f)) return 0; /* also catches NaN */ if (x >= 65535.0f) return 65535u; return (uint16_t)(x + 0.5f); } int main(void) { printf(“sat_u8(300) = %u plain cast = %u\n”, sat_u8(300), (uint8_t)300); printf(“sat_u8(-20) = %u plain cast = %u\n”, sat_u8(-20), (uint8_t)-20); printf(“sat_i16(70000)= %d plain cast = %d\n”, sat_i16(70000), (int16_t)70000); printf(“f_to_u16(1e9) = %u\n”, f_to_u16(1e9f)); printf(“f_to_u16(-5) = %u\n”, f_to_u16(-5.0f)); printf(“f_to_u16(1234.6) = %u\n”, f_to_u16(1234.6f)); return 0; }
Output (verified by compiling and running)
sat_u8(300) = 255 plain cast = 44 sat_u8(-20) = 0 plain cast = 236 sat_i16(70000)= 32767 plain cast = 4464 f_to_u16(1e9) = 65535 f_to_u16(-5) = 0 f_to_u16(1234.6) = 1235
Wrap-around versus saturation for uint8_t, input 300
Plain cast
44
a loud signal suddenly becomes quiet
Saturating
255
clips at the maximum

Example 11: Mini Exercises

Exercise 1: What is sizeof(int[3][4]) on the STM32F407?
3 × 4 × 4 = 48 bytes.
Exercise 2: What is the value of (uint8_t)(0xAB << 4)?
0xAB << 4 = 0xAB0 (as int); the low byte is 0xB0 (176).
Exercise 3: What does (int)-7.9 evaluate to?
−7 (toward zero).
Exercise 4: Write a macro that reads a 16-bit register at address 0x40004400.
#define REG16 (*(volatile uint16_t *)0x40004400UL)
Exercise 5: Is if (u8 >= 0) ever false for a uint8_t u8?
Never: an unsigned value is always ≥ 0, so the test is useless. The compiler warns with -Wtype-limits.
Exercise 6: What is sizeof('A') in C?
4 on the STM32F407 (and most platforms): a character constant has type int in C.
Exercise 7: Why use uintptr_t instead of unsigned int to hold an address?
On a 64-bit host unsigned int is only 32 bits and would truncate the pointer. uintptr_t is guaranteed to be wide enough.

Key Takeaways from the sizeof and Type Casting Examples

  • The sizeof and type casting examples confirm: PC sizes for long and pointers differ from the STM32F407 (8 versus 4 bytes).
  • sizeof(array) / sizeof(array[0]) is the idiom for element count; it fails on pointers.
  • Character constants, comparisons and promoted expressions have type int, so sizeof of them is 4.
  • Arithmetic on narrow types happens in int; narrowing happens only at the assignment or cast.
  • Mixed signed/unsigned comparisons convert to unsigned: the common source of “impossible” bugs.
  • A register macro is just a cast, a dereference and volatile; the same logic can run on a PC by changing the base address.
  • The pointer type decides the access width and the byte order is visible through byte pointers.
  • Float-to-integer casts truncate toward zero; round and clamp explicitly.

Ready for the quiz?

Next: predict sizeof output, answer casting questions and work through interview questions on type conversion.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *