sizeof in C

Previous
Next

sizeof():

  • It is library function.
  • It is used to find the size of
    • Variable
    • Data type
    • Expression
    • Array
    • String
    • Structure
    • Pointer
    • ……
  • Sizeof() function returns the size in integer form.

Finding size using variable:

#include <stdio.h>
int main()
{
	char c;
	short s;
	float f;
	double d;
	
	printf("char size : %d \n", sizeof(c));
	printf("short size : %d \n", sizeof(s));
	printf("float size : %d \n", sizeof(f));
	printf("double size : %d \n", sizeof(d));
	return 0;
}

Output:
char size : 1
short size : 2
float size : 4
double size : 8

We can also find the size of data type directly:

#include <stdio.h>
int main()
{
	printf("char size : %d \n", sizeof(char));
	printf("short size : %d \n", sizeof(short));
	printf("float size : %d \n", sizeof(float));
	printf("double size : %d \n", sizeof(double));
	return 0;
}

Output:
char size : 1
short size : 2
float size : 4
double size : 8

Finding the size of expression: In expression, which type occupies highest memory will be the output.

For example:

  • Short + Long à Long
  • Float + Double à Double
  • Char + Short à Short
#include <stdio.h>
int main()
{
	char c;
	short s;
	float f;
	double d;
	printf("char + short : %d \n", sizeof(c+s));
	printf("float + double : %d \n", sizeof(f+d));
	return 0;
}

Output:
char + short = 2
float + double = 8
Previous
Next

Add Comment

Courses Enquiry Form