Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why sizeof('a') is 4 in C? [duplicate]

Possible Duplicate:
Why are C character literals ints instead of chars?

#include<stdio.h>
int main(void)
{
    char b = 'c';
    printf("here size is %zu\n",sizeof('a'));
    printf("here size is %zu",sizeof(b));
}

here output is (See live demo here.)

here size is 4 
here size is 1

I am not getting why sizeof('a') is 4 ?

like image 375
Jeegar Patel Avatar asked Dec 28 '11 10:12

Jeegar Patel


People also ask

Why does sizeof return 4?

Since int in an integer type variable. So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.

What is sizeof () operator in C?

Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.

Is a char 4 bytes?

The char type takes 1 byte of memory (8 bits) and allows expressing in the binary notation 2^8=256 values.

What is the return of sizeof (); in what unit?

When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32-bit system can show different output while a 64-bit system can show different of same data types.


2 Answers

Because in C character constants, such as 'a' have the type int.

There's a C FAQ about this suject:

Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs).

like image 54
cnicutar Avatar answered Oct 22 '22 20:10

cnicutar


The following is the famous line from the famous C book - The C programming Language by Kernighan & Ritchie with respect to a character written between single quotes.

A character written between single quotes represents an integer value equal to the numerical value of the character in the machine's character set.

So sizeof('a') is equivalent to sizeof(int)

like image 35
Sangeeth Saravanaraj Avatar answered Oct 22 '22 19:10

Sangeeth Saravanaraj