Click here to Skip to main content
15,918,007 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when I am printing sizeof('b'); in c it is printing 4, But it should print 1 because b is not a integer ,it is a char
but when I am declaring char b; then its ascii value will also take 4 byte but then its print 1; or we can say that in that case ascii value will NOT take 4 byte after being an integer also HOW??

What I have tried:

#include<stdio.h>
 int main(){
 printf("the size of b is %d",sizeof('b')); 

 }
Posted
Updated 4-Sep-18 4:47am

Do an experiment with your current setup.

Declare a byte, char, short int, int.
Now run sizeof() on them.

Your system can have characters default to sizes other than one byte.

from a google search for "sizeof(char) in c":

Quote:
It depends what is the character and what encoding it is in: An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits. An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte). A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).Jan 31, 2011
 
Share this answer
 
This appears to the result of using a literal ('a') as the argument vs assigning 'a' to a variable first.

Character literals
In C, character literals such as 'a' have type int, and thus sizeof('a') is equal to sizeof(int).
In C++, character literals have type char, and thus sizeof('a') is equal to sizeof(char).
This difference can lead to inconsistent behavior in some code that is compiled as both C and C++.

Source: Incompatabilities between C and C++: Character literals[^]
 
Share this answer
 
In your code the 'b' isnt a char, but an unnamed variable. And this is defaulting the compiler to an int.

In programming it is best to be as precise as possible because compiler and linker may understand your code a little different than you and like to optimize it. I made lately (and again) the experience that some code in destructors is never excuted, because the optimizing process thrown it away.
 
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