C 和 C++ 中字符常量的数据类型
cc++server side programmingprogramming
在 C++ 中,字符常量的大小为 char。在 C 中,字符常量的类型为整数 (int)。因此,在 C 中,sizeof(‘a’) 对于 32 位架构为 4,CHAR_BIT 为 8。但 sizeof(char) 对于 C 和 C++ 都是一个字节。
示例
#include<stdio.h> main() { printf("%d", sizeof('a')); }
输出
4
示例
#include<iostream> using namespace std; main() { cout << sizeof('a'); }
输出
1
在两种情况下,我们做的是相同的。但在 C 中,sizeof(‘a’) 返回 4,因为它被视为整数。但在 C++ 中,它返回 1。它被视为字符。