Reputation: 966
The C11 standard says that character constants (e.g., 'x'
) are of type int
, not char
. This surprised and confused me (especially as a relative beginner). I came across this answer Why are C character literals ints instead of chars?, which somewhat cleared things up, but still left me wondering why it seems to be routine practice (at least in all the books and tutorials I've come across) to assign character constants to variables that are declared to be of type char
. For example, why do we do
char initial = 's';
and not
int initial = 's';
And then, what happens when a constant of type int
is assigned to a variable of type char
? Is it switched into type char
?
Upvotes: 3
Views: 288
Reputation: 727077
The fact that character literals are of type int
is only a half of the story. The other half is that their value is in the range of char
. This is critical, because if you assign
char a = 65;
you get no warning, but if you do
char b = 56789;
you get a warning.
why do we do
char initial = 's'
and notint initial = 's'
?
This lets you avoid casting when assigning the variable to another variable of type char
, or to an element of a char[]
array:
char str[2];
str[0] = initial; // no cast when "initial" is of type "char"
There is one situation when you need to use int
for variables storing char
- when you use a getc
/ fgetc
functionality, the result must be an int
, not a char
, in order to allow comparison with EOF
.
Upvotes: 4
Reputation: 154582
Consider float x = 3.0;
That sets a double
3.0
to a float
. Code could have been float x = 3.0f;
. The end result is the same.
Same with char ch = 5;
. vs char ch = (char)5;
In both case, ch
gets the same value.
In the end, consider C was originally focused on types int
, and double
- that's it. Types like float
, short
, char
, long
,... are just deviations from the truly core types of C. (Even unsigned
, bool
were afterthoughts.)
what happens when a constant of type int is assigned to a variable of type char? Is it switched into type char?
The constant remains the type it was. Assigning a constant of type int
to a char
does not change the type of the constant. What can change is the value from the int
when the original int
value is outside the range of char
and then saved in a char
.
Upvotes: 2
Reputation: 24100
If an int
value is assigned to char
variable, the value is converted to type char
.
There are a few reasons for declaring a variable char
rather than int
. One is to save memory (although this is more relevant when used in an array or other aggregate). Another is to make it clear that it is intended to hold a char
value. Another is to implicitly restrict the range of its value. And in some cases you may wish to take its address to obtain a char *
, in which case you would not be able to use an int
variable.
Upvotes: 1