Sizeof Operator in C programming language
Sizeof Operator in C programming:
- sizeof operator used to calculate the sizeof variable, constant or datatype
- its unary operator means works on a single operand
- sizeof operator returns the size of given input
Syntax :
result = sizeof(typeName)
typeName can be variable, constant or datatype.
Example :
printf(“Size of Integer : %ld \n”, sizeof(int))
Output :
Size of Integer: 4
Note: If you may thinking why I used %ld format specifier Because sizeof operator returns the output in size_t format. it is an unsigned int format.
Program to calculate the sizes of all data types :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include<stdio.h> int main(){ printf("Size of Character : %ld \n", sizeof(char)); printf("Size of short Integer : %ld \n", sizeof(short int)); printf("Size of Integer : %ld \n", sizeof(int)); printf("Size of Long Integer : %ld \n", sizeof(long int)); printf("Size of Float : %ld \n", sizeof(float)); printf("Size of Double : %ld \n", sizeof(double)); printf("Size of Long Double : %ld \n", sizeof(long double)); printf("Size of Integer Pointer : %ld \n", sizeof(int*)); printf("Size of Character Pointer : %ld \n", sizeof(char*)); printf("Size of Float Pointer : %ld \n", sizeof(float*)); return 0; } |
Output :
1 2 3 4 5 6 7 8 9 10 11 12 |
root@ubuntu:/home/venkatesh# gcc sizeof.c root@ubuntu:/home/venkatesh# ./a.out Size of Character : 1 Size of Integer : 4 Size of short Integer : 2 Size of Long Integer : 8 Size of Float : 4 Size of Double : 8 Size of Long Double : 16 Size of Integer Pointer : 8 Size of Character Pointer : 8 Size of Float Pointer : 8 |
Note: I am using GCC compiler on Ubuntu system with 64 bit OS. So if you use any other compiler like turbo C, your output might differ. But you need to note that sizes of datatypes are platform depended.
Fun Fact :
sizeof operator looks like a Function ( because of the parenthesis ) but it’s an operator.
what would be the output of following program
int main()
{
printf(“%ld\n”,sizeof(sizeof(‘A’)));
}