"Old Wolf" <ol*****@inspir e.net.nz> writes:
Neil Kurzman wrote: JS wrote: "Ben Pfaff" <bl*@cs.stanfor d.edu> skrev:
"JS" <dsa.@asdf.co m> writes:
> I read in K&R page 204 that sizeof use on a char returns 1.
> But when I write the following I get 4!
>
> printf("%d\n",s izeof('g'));
In C, character constants have type `int', so sizeof 'g' is equal
to sizeof(int).
Why do they write char if they mean int?
lookup Integer Promotion
This has nothing to do with integer promotion. The argument
to 'sizeof' does not undergo any promotions or conversions.
It's relevant, but only very indirectly. Since expressions of type
char are almost always promoted to int, there would be little point
(in C) in making character constants be of type char rather than of
type int.
This is part of the rationale for why the standard is the way it is;
it's not something from which you can logically infer that character
constants are of type int. The standard could just as easily have
said that character constants are of type char; they would then be
immediately promoted to int, so it would make a difference only when
the character constant is the operand of sizeof.
(Note that if plain char were unsigned, and sizeof(int)==1 (which
requires CHAR_BIT>=16), character constants of type char would promote
to unsigned int rather than int, but that doesn't apply to most
implementations .)
The real answer to "Why are character constants of type int rather
than char?" is "Because the standard says so". *Why* the standard
says so is another question.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.