Reputation: 421
I have a small snippet of code. When I run this on my DevC++ gnu compiler it shows the following output:
main ()
{ char b = 'a';
printf ("%d,", sizeof ('a'));
printf ("%d", sizeof (b));
getch ();
}
OUTPUT: 4,1
Why is 'a'
treated as an integer, whereas as b
is treated as only a character constant?
Upvotes: 4
Views: 1051
Reputation: 145919
Because character literals are of type int
and not char
in C.
So sizeof 'a' == sizeof (int)
.
Note that in C++, a character literal is of type char
and so sizeof 'a' == sizeof (char)
.
Upvotes: 9
Reputation: 4599
From IBM XL C/C++ documentation
A character literal contains a sequence of characters or escape sequences enclosed in single quotation mark symbols, for example 'c'. A character literal may be prefixed with the letter L, for example L'c'. A character literal without the L prefix is an ordinary character literal or a narrow character literal. A character literal with the L prefix is a wide character literal. An ordinary character literal that contains more than one character or escape sequence (excluding single quotes ('), backslashes () or new-line characters) is a multicharacter literal.
Character literals have the following form:
.---------------------.
V |
>>-+---+--'----+-character-------+-+--'------------------------><
'-L-' '-escape_sequence-'
At least one character or escape sequence must appear in the character literal. The characters can be from the source program character set, excluding the single quotation mark, backslash and new-line symbols. A character literal must appear on a single logical source line.
C A character literal has type int
Upvotes: 0
Reputation: 1105
In C, a character literal has type int.
In C++, a character literal that contains only one character has type char, which is an integral type.
In both C and C++, a wide character literal has type wchar_t, and a multicharacter literal has type int.
Upvotes: 0
Reputation: 320777
That's just the way it is in C. That's just how the language was originally defined. As for why... Back then virtually everything in C was an int
, unless there was a very good reason to make it something else. So, historically character constants in C have type int
.
Note BTW, in C nomenclature 'a'
is called constant, not literal. C has string literals and no other literals.
Upvotes: 1