如何在C中为整数类型变量赋值? [英] How can you assign a character value to a integer type variable in C?
问题描述
在C中,
...
int num = 'a';
...
我的问题很简单。如何在整数类型变量中指定诸如0,a,b之类的字符而不会在C语言中出现任何类型错误?
My question is simple. How can you assign a character such as '0', 'a', 'b' to an integer type variable without getting any type error in C language?
推荐答案
由于历史原因(大多数情况下),字符常量在C中的类型为 int
。
For historical reasons (mostly), character constants are of type int
in C.
但是,即使它们不是,初始化如
But even if they weren't, an initialization like
int num = 'a';
或像
num = 'a';
仍然完全合法。可以将任何数字类型的值分配给任何(其他)数字类型的变量,并且将隐式转换该值(这可能涉及表示的更改和/或溢出的风险)。
would still be perfectly legal. A value of any numeric type may be assigned to a variable of any (other) numeric type, and the value will be implicitly converted (which may involve a change of representation and/or a risk of overflow).
和 char
,以及它的亲戚 unsigned char
和 signed char
,是数字类型,特别是整数类型。
And char
, along with its relatives unsigned char
and signed char
, are numeric types, specifically integer types.
这篇关于如何在C中为整数类型变量赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!