Possible Duplicate:
Why are C character literals ints instead of chars?
folks,
I tried to print out the size of char in C. With the following code, I got the result output as
int, 4
char, 1
char?, 4
Why is the last one not the same as the 2nd one? Thanks.
#include <stdio.h>
main()
{
int a = 2;
char b = '2';
printf("int, %d\n",sizeof(a));
printf("char, %d\n",sizeof(b));
printf("char?, %d\n",sizeof('a'));
}
Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use. Here, a signed character is capable of holding negative values. Thus, the defined range here is -128 to +127.
While their size is the same in practice, their alignment requirements are not. If you are doing "kernel coding", that already limits the number of platforms the code can run on. Check with the OS spec what is supported.
Is a char always 1 byte? Yes, in C a char is by definition 1 byte in size. But a byte is not necessarily 8 bits. The number of bits in a byte, or in a char, is specified by the value of the CHAR_BIT macro, defined in <limits.
In C, a character constant like 'a'
has type int
.
This is different from C++ and Java, where a character constant like 'a'
has type char
,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With