c++ - C/C++ 中字符的大小 ('a' )

标签 c++ c types

C 和 C++ 中字符的大小是多少?据我所知,在 C 和 C++ 中,char 的大小都是 1 个字节。

In C:

#include <stdio.h>
int main()
{
    printf("Size of char : %d\n", sizeof(char));
    return 0;
}

In C++:

#include <iostream>
int main()
{
    std::cout << "Size of char : " << sizeof(char) << "\n";
    return 0;
}

毫不奇怪,它们都给出了输出:Size of char : 1

现在我们知道字符表示为'a','b','c','|' ,...所以我只是将上面的代码修改为:

在 C 中:

#include <stdio.h>
int main()
{
    char a = 'a';
    printf("Size of char : %d\n", sizeof(a));
    printf("Size of char : %d\n", sizeof('a'));
    return 0;
}

Output:

Size of char : 1
Size of char : 4

在 C++ 中:

#include <iostream>
int main()
{
    char a = 'a';
    std::cout << "Size of char : " << sizeof(a) << "\n";
    std::cout << "Size of char : " << sizeof('a') << "\n";
    return 0;
}

Output:

Size of char : 1
Size of char : 1

为什么 sizeof('a') 在 C 和 C++ 中返回不同的值?

最佳答案

在 C 中,字符常量 的类型如 'a' 实际上是一个 int,大小为 4(或其他一些实现相关的值)。在 C++ 中,类型为 char,大小为 1。这是两种语言之间许多细微差异之一。

关于c++ - C/C++ 中字符的大小 ('a' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21629472/

相关文章:

c++ - 为什么默认构造函数只适用于类指针?

c++ - ELI5 : What is the data type of `int *p[]`

database - 应对数据库身份/自动编号最大化的策略

C++将局部变量存储到 vector 中可防止它在超出范围时被破坏

C++转义控制字符

c++ - 用C++标准库分析Clang线程安全

c - C 语言中的有限状态机

C - Return 语句不退出 void 函数

c# - 将对象动态转换为基类型

java - 类型参数 E 隐藏了类型 E。尝试了不同的变体,但仍然无法修复