如果字符常量是‘int’类型的,为什么它们被分配给‘char’类型的变量? [英] If character constants are of type `int', why are they assigned to variables of type `char`?
问题描述
C11 标准规定字符常量(例如,'x'
)属于 int
类型,而不是 char
类型.这让我感到惊讶和困惑(尤其是作为一个相对的初学者).我遇到了这个答案 为什么 C 字符文字是整数而不是字符?,这在某种程度上澄清了问题,但仍然让我想知道为什么将字符常量分配给声明为的变量似乎是常规做法(至少在我遇到的所有书籍和教程中)char
类型.例如,我们为什么要这样做
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';
而不是
int initial = 's';
然后,当 int
类型的常量被分配给 char
类型的变量时会发生什么?是否切换到char
类型?
And then, what happens when a constant of type int
is assigned to a variable of type char
? Is it switched into type char
?
推荐答案
字符文字属于 int
类型这一事实只是故事的一半.另一半是它们的值在char
的范围内.这很关键,因为如果你分配
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;
您收到警告.
为什么我们做 char initial = 's'
而不是 int initial = 's'
?
why do we do
char initial = 's'
and notint initial = 's'
?
这使您可以在将变量分配给另一个 char
类型的变量或 char[]
数组的元素时避免强制转换:
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"
有一种情况,您需要使用 int
来存储 char
的变量 - 当您使用 getc
/fgetc
功能,结果必须是 int
,而不是 char
,以便与 EOF
进行比较.
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
.
这篇关于如果字符常量是‘int’类型的,为什么它们被分配给‘char’类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!