问题源于本周的系统级编程的作业,感觉很神奇,由于平时c/cpp用的少,记录一下。
问题描述
直接上代码,在gcc -m64 <filename>.c命令下编译,可以猜猜输出是什么
#include <stdio.h>
int main()
{
printf("%d", sizeof('a'));
return 0;
}
结果是4。同样是上面的代码,在g++ -m64 <filename>.c命令下编译,结果却是1。

解释
在c99中,'a’叫做 整型字符常量(integer character constant),当成int处理,因此结果就等于sizeof(int)。
而在cpp中,'a’叫做 字符字面量(character literal),当成char处理,因此结果等于sizeof(char)。
附上一段c99的原生定义:
An integer character constant is a sequence of one or more multibyte characters enclosed
in single-quotes, as in ‘x’. A wide character constant is the same, except prefixed by the
letter L. With a few exceptions detailed later, the elements of the sequence are any
members of the source character set; they are mapped in an implementation-defined
manner to members of the execution character set."“An integer character constant has type int. The value of an integer character constant
containing a single character that maps to a single-byte execution character is the
numerical value of the representation of the mapped character interpreted as an integer.
The value of an integer character constant containing more than one character (e.g.,
‘ab’), or containing a character or escape sequence that does not map to a single-byte
execution character, is implementation-defined. If an integer character constant contains
a single character or escape sequence, its value is the one that results when an object with
type char whose value is that of the single character or escape sequence is converted to
type int.”
本文探讨了在C/C++中使用'sizeof('a')'时的不同结果。在C99中,'a'被视为整型字符常量,其大小等于int类型。而在C++中,'a'被当作字符字面量,其大小为char类型。文章深入分析了这一现象背后的原因,并引用了C99标准的部分原文。
952

被折叠的 条评论
为什么被折叠?



