Use of sizeof() operator in C
The C compilaer provides an operator name sizeof() that is responsible to return memory space require in bytes. A sizeof() operator can accept a variable, datatype, object etc as an argument and returns a memory space required in byte.
Syntax:- To use sizeof() operator
Var = sizeof(var/datatype/object);
var = sizeof var/datatype/object;
var= sizeof expression;
or
printf(“<format specifier>”,sizeof(var/datatype));
Example:-
void main()
{
int a,char ch;
clrscr();
printf(“Capacity of a =%d”,sizeof(a));
printf(“\n Capacity of ch=%d”,sizeof(ch));
printf(“\n long int =%d”,sizeof(long int));
printf(“\n short int=%d”,sizeof(short int));
printf(“\n float =%d”,sizeof(float));
printf(“\n long float =%d”,sizeof(long float));
printf(“\n Double=%d”,sizeof(double));
printf(“\n long Double=%d”,sizeof(long double));
getch();
}
OUTPUT-----à
Capacity of a=2
Capacity of ch=1
long int=4
short int=2
float=4
long float=8
double= 8
long double=10
Explanation:-
(1) In C language when we use a value between -32767 and 32767 then it by default promote into int datatype and if we exceed this range then value by default promote into long int.
Example:-
(a) printf(“%d”,sizeof(2500));
|
Output--à 2
(b) printf(“%d”,sizeof 25*2);
Output---à 6
(c) printf(“%d”,sizeof 40000);
Output---à 4
(d) printf(“%d”,sizeof 25+5);
|
Output---à 7
(e) printf(“%d”,sizeof -40*3%2);
Output---à 0
(2) In C language, a fractional value by default promote into double and if we use symbol (F/f) with value then it promote into float.
Example:-
(a) printf(“%d”,sizeof(4.5));
Output---à 8
(b) printf(“%d”,sizeof 4.5f));
Output---à 4
(c) printf(“%d”,sizeof 4.5-3);
|
Output---à 5
(d) printf(“%d”,sizeof 2.8f-2*5);
Output---à -6
(e) printf(“%d”,sizeof ‘A’);
Output---à 2
(f) char *p;
printf(“%d”,sizeof p);
Output---à 2
(g) float *p;
printf(“%d”,sizeof p);
Output---à 2
NOTE—In C language, a pointer always allocates 2 bytes memory space.
Example:- int num[3];
(a) printf(“%d”,sizeof num[0]);
Output-----à 2
(b) prinft(“%d”, sizeof num);
Output---à 6
Comments
Post a Comment