sizeof() operator

C program to print size of variables using sizeof() operator.

Program

#include<stdio.h>
#include<conio.h>
void main()
{
    char    a       ='C';
   	int     b       =644;
   	float   c       =45.6;
   	double  d       =123.80;

   	printf("\nSize of a: %d",sizeof(a));
   	printf("\nSize of b: %d",sizeof(b));
   	printf("\nSize of c: %d",sizeof(c));
   	printf("\nSize of d: %d",sizeof(d));

   	printf("\n\nSize of char: %d",sizeof(char));
    printf("\nSize of int: %d",sizeof(int));
   	printf("\nSize of float: %d",sizeof(float));
   	printf("\nSize of double: %d",sizeof(double));

    printf("\n\nSize of expression(4 + 6.5): %d",sizeof(4 + 6.5));
    printf("\nSize of expression(4 + 6.5f): %d",sizeof(4 + 6.5f));
    printf("\nSize of expression(b + c): %d",sizeof(b + c));

	getch();

}

Output

Size of a: 1
Size of b: 4
Size of c: 4
Size of d: 8

Size of char: 1
Size of int: 4
Size of float: 4
Size of double: 8

Size of expression(4 + 6.5): 8
Size of expression(4 + 6.5f): 4
Size of expression(b + c): 4

Explanation

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

sizeof() operator can be used in various ways.
sizeof(data type)
sizeof(variable-name)
sizeof(expression)

The above program shows the use of sizeof() operator in all the three ways.

First one is sizeof(data type). In above example, 4 basic datatypes are considered.
sizeof(char) = 1
sizeof(int) = 4
sizeof(float) = 4
sizeof(double) = 8

Second one is sizeof(variable-name). In above example four variables 'a', 'b', 'c' and 'd' are taken of the types char, int, float and double.
So, sizeof(a) = 1 because 'a' is of char type
sizeof(b) = 4 because 'b' is of int type
sizeof(c) = 4 because 'c' is of float type
sizeof(d) = 8 because 'd' is of double type

Third one is sizeof(expression).
sizeof(4 + 6.5) is 8. Now let us understand this.
C performs implicit data type conversion to make sure all operands in an expression are of similar type. All operands of expression are converted to higher type i.e. double type (since 6.5 is of double type). Hence the expression sizeof(4 + 6.5) is equivalent to sizeof(double).

Similarly, in case of sizeof(b+c), variable 'b' has integer data type and variable 'c' has float data type. 'b' will be implicitly converted to float data type and hence the result will be float value. so, this calls for the statement sizeof(float).

Now, let us consider the statement sizeof(4 + 6.5f).
In this case first operand '4' is of integer type, whereas second operator '6.5f' is of float type instead of double type. In C, value '6.5' is considered as double by default. If we want the value to be of float type, then value is followed by 'f' character. So, '6.5f' is considered to be of float data type and hence the result will be the size of float data type.