Data types in C: solved exercise
If you searched for data types in C solved exercise, this example helps you understand type sizes and basic casts.
Problem statement
Create a program that:
- prints sizes of common numeric types,
- casts
floattoint, - casts
inttodouble.
C solution
#include <stdio.h>
int main(void) {
int n = 42;
float x = 7.75f;
printf("sizeof(char): %zu\n", sizeof(char));
printf("sizeof(int): %zu\n", sizeof(int));
printf("sizeof(float): %zu\n", sizeof(float));
printf("sizeof(double): %zu\n", sizeof(double));
int truncated = (int)x;
double converted = (double)n;
printf("float -> int: %d\n", truncated);
printf("int -> double: %.2f\n", converted);
return 0;
}Expected output
sizeof(char): 1
sizeof(int): 4
sizeof(float): 4
sizeof(double): 8
float -> int: 7
int -> double: 42.00Common mistakes
- Assuming fixed sizes across every platform.
- Mixing types without casts and losing precision.
- Ignoring truncation when converting
floattoint.
Practical use
Understanding types and casts in C helps prevent precision bugs, overflow issues, and unexpected behavior.
Recommended next exercise
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Is sizeof(int) always 4?
Not always. It is often 4 in practice, but it depends on architecture and compiler.
What happens when casting float to int?
The decimal part is truncated, not rounded.
When should I use explicit casts?
When you want predictable conversions and to avoid ambiguous implicit behavior.