C 语言和 C++ 语言中字符常量的类型


在 C++ 中字符常量的大小是 char。在 C 语言中字符常量的类型是整型(int)。因此,在 C 语言中 sizeof(‘a’) 对于 32 位架构是 4,而 CHAR_BIT 为 8。但是,对于 C 语言和 C++ 语言来说 sizeof(char) 都是一个字节。

示例

 实时演示

#include<stdio.h>
main() {
   printf("%d", sizeof('a'));
}

输出

4

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例

 实时演示

#include<iostream>
using namespace std;
main() {
   cout << sizeof('a');
}

输出

1

在这两种情况下,我们都做了相同的事情。但在 C 语言中,sizeof(‘a’) 返回 4,因为它被视为整型。但在 C++ 语言中,它返回 1,因为它被视为字符。

更新于: 2019-7-30

830 次观看

开启你的 职业生涯

完成课程获得认证

开始
广告