sizeof() operator in C programming

Size of a data type is machine dependent and vary from compiler to compiler. However, in programming there exists situations when we need to know total bytes a type occupies in memory. To find exact size of a type in C programming we use sizeof() operator.

sizeof() is a special operator used to find exact size of a type in memory. The sizeof() operator returns an integer i.e. total bytes needed in memory to represent the type or value or expression.

The sizeof() is much used operator by programmers. It is very useful for developing portable programs.

Read more – Operators in C programming

Syntax to use sizeof() operator

sizeof() operator can be used in various way.

sizeof(type)
sizeof(variable-name)
sizeof(expression)

Example to use sizeof() operator

#include <stdio.h>

int main()
{
    int integerVar;

    printf("Size of char = %d\n", sizeof(char));                   // sizeof(type)
    printf("Size of int = %d\n", sizeof(integerVar));              // sizeof(variable-name)
    printf("Size of expression (3+2.5) = %d\n", sizeof(3 + 2.5));  // sizeof(expression)

    return 0;
}

Output of the above program.

Size of char = 1
Size of int = 4
Size of expression (3+2.5) = 8

Wondering, how sizeof(3 + 2.5) is 8? C performs integer promotion to make sure all operands in an expression are of similar type. All operands of expression is promoted to higher type i.e. double type (since 2.5 is of double type). Hence the expression sizeof(3 + 2.5) is equivalent to sizeof(double).

Note: The above program is compiled on GCC C compiler. The results may vary from compiler to compiler.

Program to find size of data types

/**
 * C program to find size of basic and derived types using sizeof() operator
 */

#include <stdio.h>

int main()
{
	printf("sizeof(char) = %d\n\n", sizeof(char));
	
	printf("sizeof(short) = %d\n", sizeof(short));
	printf("sizeof(int) = %d\n", sizeof(int));
	printf("sizeof(long) = %d\n", sizeof(long));
	printf("sizeof(long long) = %d\n\n", sizeof(long long));
	
	printf("sizeof(float) = %d\n", sizeof(float));
	printf("sizeof(double) = %d\n", sizeof(double));
	printf("sizeof(long double) = %d\n", sizeof(long double));
	
	return 0;
}

Output

sizeof(char) = 1

sizeof(short) = 2
sizeof(int) = 4
sizeof(long) = 4
sizeof(long long) = 8

sizeof(float) = 4
sizeof(double) = 8
sizeof(long double) = 12

The above program we used sizeof(type) to find its size. However, it is often recommended to use variable name i.e. sizeof(variable-name) instead of type name. As if a type has modified in the program the whole program needs not to be changed.