0
0
Cprogramming~5 mins

Storage size overview in C

Choose your learning style9 modes available
Introduction

Knowing storage sizes helps you understand how much memory different data types use in your program.

When you want to save memory by choosing the right data type.
When you need to know how much space variables take in memory.
When you are working with hardware or embedded systems with limited memory.
When debugging memory-related issues like overflow or alignment.
When optimizing your program for speed and size.
Syntax
C
sizeof(type_or_variable)

sizeof returns the size in bytes of a data type or variable.

You can use it with a type name inside parentheses or with a variable name.

Examples
Gets the size of the int type in bytes.
C
sizeof(int)
Gets the size of the char type, usually 1 byte.
C
sizeof(char)
Gets the size of the variable x which is an int.
C
int x; sizeof(x);
Sample Program

This program prints the size in bytes of common C data types using sizeof.

C
#include <stdio.h>

int main() {
    printf("Size of char: %zu byte(s)\n", sizeof(char));
    printf("Size of int: %zu byte(s)\n", sizeof(int));
    printf("Size of float: %zu byte(s)\n", sizeof(float));
    printf("Size of double: %zu byte(s)\n", sizeof(double));
    return 0;
}
OutputSuccess
Important Notes

Sizes can vary depending on your computer and compiler.

sizeof(char) is always 1 byte by definition.

Use %zu in printf to print sizeof results safely.

Summary

sizeof tells you how many bytes a type or variable uses.

Knowing sizes helps manage memory and optimize programs.

Always check sizes when working on different systems or with special data types.