Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, why is sizeof(char) 1, when 'a' is an int?

Tags:

c

char

int

sizeof

size

I tried

printf("%d, %d\n", sizeof(char), sizeof('c'));

and got 1, 4 as output. If size of a character is one, why does 'c' give me 4? I guess it's because it's an integer. So when I do char ch = 'c'; is there an implicit conversion happening, under the hood, from that 4 byte value to a 1 byte value when it's assigned to the char variable?

like image 873
legends2k Avatar asked Feb 12 '10 13:02

legends2k


People also ask

Is sizeof char guaranteed to be 1?

Even if you think of a “character” as a multi-byte thingy, char is not. sizeof(char) is always exactly 1. No exceptions, ever.

Why is a char an integer in C?

Software Engineering C C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255.

Is a char the same size as an int?

Both are platform dependant. sizeof(int) is the same as sizeof(char*).

What is the sizeof int in C?

sizeof(* int) returns the size of the address value, that is, a byte. address that points to a byte position in memory that stores an int. value. The address values are typically 4 byte integers themselves on a. 32 bit system, so sizeof(*int) would return 4.


1 Answers

In C 'a' is an integer constant (!?!), so 4 is correct for your architecture. It is implicitly converted to char for the assignment. sizeof(char) is always 1 by definition. The standard doesn't say what units 1 is, but it is often bytes.

like image 191
Richard Pennington Avatar answered Oct 03 '22 08:10

Richard Pennington