[英]C output question.Can anyone explain this output?
#include<stdio.h>
void main()
{
printf("%d",'AA');
}
I was expecting an error there but the program ran and output was 16705. Can anyone please explain this?我期待那里出现错误,但程序运行并且 output 是 16705。有人可以解释一下吗?
Can anyone please explain this?
谁能解释一下?
The 'AA'
is a multi-character character constant. 'AA'
是一个多字符字符常量。 It has the type int
.它的类型为
int
。 It's value is implementation-defined.它的值是实现定义的。
"Implementation" here is the compiler and your compiler has rules to which int
value 'AA'
is mapped to.这里的“实现”是编译器,您的编译器具有将
int
值'AA'
映射到的规则。 The mapping seems to be easy.映射似乎很容易。 Because I don't know your compiler, I am guessing it.
因为我不知道你的编译器,我猜它。 Consult your compiler documentation to be sure.
请查阅您的编译器文档以确定。
'AA'
maps to a value 'A' << 8 | 'A'
'AA'
映射到值'A' << 8 | 'A'
'A' << 8 | 'A'
. 'A' << 8 | 'A'
。 Bit shifted 'A'
by a byte with another 'A'
.用另一个
'A'
将'A'
位移一个字节。 You system most probably uses ASCII to represent characters.您的系统很可能使用 ASCII 来表示字符。 The
'A'
maps in ASCII to a value 65
in decimal ( 0x41
in hex). ASCII 中的
'A'
映射到十进制值65
(十六进制中的0x41
)。 Calculating 0x41 << 8 | 0x41
计算
0x41 << 8 | 0x41
0x41 << 8 | 0x41
gives the value of 16705
in decimal. 0x41 << 8 | 0x41
给出十进制值16705
。 Because this is an int
value, you can use %d
to print the result.因为这是一个
int
值,所以您可以使用%d
打印结果。 So your code is equivalent to printf("%d\n", 16705)
.所以你的代码相当于
printf("%d\n", 16705)
。
'AA'
is an exotic beast. 'AA'
是一种奇异的野兽。 It's a character literal, but ASCII does not have a single character 'AA'
.这是一个字符文字,但 ASCII 没有单个字符
'AA'
。 This explains why you get a non-ASCII value instead.这解释了为什么你会得到一个非 ASCII 值。
this code run because the char data type is a number and you have request ho print the real number of 'AA'此代码运行是因为 char 数据类型是数字,并且您已请求打印 'AA' 的实数
https://en.wikipedia.org/wiki/C_data_types https://en.wikipedia.org/wiki/C_data_types
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.