C Program to Find the Size of Data Types

Understanding memory allocation is crucial for efficient C programming. Different data types occupy different amounts of memory depending on the compiler and machine architecture.

Concept Overview

The `sizeof` operator is a compile-time unary operator used to compute the size of its operand in bytes. It is essential for writing portable code and for tasks like dynamic memory allocation.

Program

C
#include <stdio.h>

int main() {
    // Printing size of various data types using the sizeof operator
    printf("Size of char: %zu byte\n", sizeof(char));
    printf("Size of int: %zu bytes\n", sizeof(int));
    printf("Size of short int: %zu bytes\n", sizeof(short int));
    printf("Size of long int: %zu bytes\n", sizeof(long int));
    printf("Size of float: %zu bytes\n", sizeof(float));
    printf("Size of double: %zu bytes\n", sizeof(double));
    printf("Size of long double: %zu bytes\n", sizeof(long double));

    return 0;
}

Sample Output

Size of char: 1 byte
Size of int: 4 bytes
Size of short int: 2 bytes
Size of long int: 8 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of long double: 16 bytes

Explanation

  • The `sizeof` operator returns a value of type `size_t`. The correct format specifier to use is `%zu`.
  • A `char` is guaranteed to be 1 byte, but others like `int` can be 2 or 4 bytes depending on the system.
  • Modifier keywords like `short` and `long` change the memory allocated to basic types.
  • Using `sizeof` ensures your program remains portable across different operating systems (32-bit vs 64-bit).
Note: Note: The actual output might vary slightly based on whether you are using a 32-bit or 64-bit compiler.