如何将字符值分配给 C 中的整数类型变量? [英] How can you assign a character value to a integer type variable in C?
问题描述
在 C 中,
...
int num = 'a';
...
我的问题很简单.如何在 C 语言中将 '0'、'a'、'b' 等字符分配给整数类型变量而不会出现任何类型错误?
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屋!