简体   繁体   English

为什么我们可以将整数分配给char变量

[英]Why can we assign integers to a char variable

I randomly surfed on StackOverflow. 我随机在StackOverflow上冲浪。 As I saw a question I became clueless. 当我看到一个问题时,我变得一无所知。 Why can we assign Integer values to a char variable? 为什么我们可以将整数值分配给char变量?

Code snippet : 程式码片段

#include <stdio.h>
int main()
{
    char c = 130;
    unsigned char f = 130;

    printf("c = %d\nf = %d\n",c,f);
    return 0;
}

Output: 输出:

c = -126
f = 130

I always thought values have to be assigned to the right type indentifier, why can we do that? 我一直认为必须将值分配给正确的类型标识符,为什么我们可以这样做呢?

That's because char is an integer type (the smallest one) and values of different integer types can be implicitly converted. 这是因为char是一种整数类型(最小的一种),并且可以隐式转换不同整数类型的值。 But beware that your example code has implementation defined behavior on a typical machine with signed 8bit char *): 130 overflows (the maximum value would be 127 ) and the result of overflowing a signed integer type during conversion is implementation defined . 但是请注意,示例代码在具有签名 8bit char *的典型机器上具有实现定义的行为130溢出(最大值为127 ),并且在转换期间溢出有符号整数类型的结果是实现定义的

You might have asked this question because you thought char is for storing characters. 您可能会问这个问题,因为您认为char是用于存储字符的。 This is actuall true, but characters are numbers. 这是事实,但字符数字。 See Character Encoding for more details. 有关更多详细信息,请参见字符编码


*) whether char (without explicit signed or unsigned ) is signed is implementation-defined, as is the number of bits, but there must be at least 8. *)是否对char (无显式signedunsigned )进行签名是由实现定义的,位数也是如此,但必须至少为8。

Quoting C11 , chapter §6.5.16.1p2 引用C11 ,第§6.5.16.1p2

In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand. 在简单赋值(=)中,将右操作数的值转换为赋值表达式的类型,并替换存储在由左操作数指定的对象中的值。

This implies that the RHS in an assignment operator is implicitly converted to the type of the variable on the LHS. 这意味着赋值运算符中的RHS被隐式转换为LHS上变量的类型。 In your case, the integer constant is converted to char type. 在您的情况下,整数常量将转换为char类型。

Also, there is no char constant in C. The character constants like 'a' , 'B' are all of int type. 另外,C中没有char常量。像'a''B'这样的字符常量都是int类型的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM