Data types in C: solved exercise with sizeof and casts

  2 minutes

If you searched for data types in C solved exercise, this example helps you understand type sizes and basic casts.

Create a program that:

  • prints sizes of common numeric types,
  • casts float to int,
  • casts int to double.
#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;
}
sizeof(char): 1
sizeof(int): 4
sizeof(float): 4
sizeof(double): 8
float -> int: 7
int -> double: 42.00
  • Assuming fixed sizes across every platform.
  • Mixing types without casts and losing precision.
  • Ignoring truncation when converting float to int.

Understanding types and casts in C helps prevent precision bugs, overflow issues, and unexpected behavior.

If you want a complete path with progressive difficulty:

Not always. It is often 4 in practice, but it depends on architecture and compiler.

The decimal part is truncated, not rounded.

When you want predictable conversions and to avoid ambiguous implicit behavior.