Click here to Skip to main content
15,911,707 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
int main ()
{
Char a='b';
Printf ("%d", sizeof ('b');
Printf ("\n%d", sizeof (a));

}

Output:
4
1
Why should i get different output though i am passing the same value.

What I have tried:

I already googled my query and found that C considers character literal as integer type hence sizeof ('b')reurns 4.
But i am getting confused here. I am passing the same value both times, still getting different values.

Please guide me here.
Thanks.
Posted
Updated 14-Aug-18 21:27pm

To add to what OriginalGriff has said. Although variable a will be allocated as 4 bytes, it has been declared as a char type. And since a char is only one byte, the compiler returns its size as 1.
 
Share this answer
 
Comments
Member 13922884 15-Aug-18 3:49am    
Ok. By default, character literal are treated as integer in C. Hence i am getting the output as 4 in 1st case. In the second case, since i have declared it as a char data type the sizeof () returns its size as 1 (though in memory it takes 4 bytes).
Correct me if i am wrong in my understanding here.

Thanks.
Richard MacCutchan 15-Aug-18 4:08am    
Yes, that is correct. The sizeof operator is a compile time operator, so it has limited use in most programs.
KarstenK 15-Aug-18 3:52am    
The var needs only 1 byte, but the system is padding 3 bytes to meet the 4 byte standard size. Couldnt this changed by #pragma padding?
Richard MacCutchan 15-Aug-18 4:09am    
Yes, but I do not think we want to confuse a beginner with pragmas at this point.
Member 13922884 15-Aug-18 4:11am    
Ok. Thank you!!
When you allocate memory, it needs to be allocated in multiples of a sensible size: the system memory unit. For a 32 or 64 bit system that tends to be 32 bits, or 4 bytes - because that is the size of a memory fetch / register. If you allocate single bytes, then that gives you problems with the next allocation you do, as it might be partly in one fetch and partly in another.
So when you use a char literal like 'b' it needs to be stored in your compiled program somewhere, and it's stored as an integer - taking up a whole system memory unit - to make it easier for every thing. So when you read the size, you get more than you bargained for!

Basically, don't worry about it - it's not something you will need to do in the "real world".
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900