Size of character (#39;a#39;) in C/C++(C/C++ 中字符 (a) 的大小)
问题描述
C 和 C++ 中字符的大小是多少?据我所知,C 和 C++ 中 char 的大小都是 1 个字节.
What is the size of character in C and C++ ? As far as I know the size of char is 1 byte in both C and C++.
在 C:
#include <stdio.h>
int main()
{
printf("Size of char : %d
", sizeof(char));
return 0;
}
在 C++ 中:
#include <iostream>
int main()
{
std::cout << "Size of char : " << sizeof(char) << "
";
return 0;
}
不出所料,他们都给出了输出:字符大小:1
No surprises, both of them gives the output : Size of char : 1
现在我们知道字符表示为'a'
,'b'
,'c'
,'|'
,... 所以我只是将上面的代码修改为这些:
Now we know that characters are represented as 'a'
,'b'
,'c'
,'|'
,... So I just modified the above codes to these:
在 C:
#include <stdio.h>
int main()
{
char a = 'a';
printf("Size of char : %d
", sizeof(a));
printf("Size of char : %d
", sizeof('a'));
return 0;
}
输出:
Size of char : 1
Size of char : 4
在 C++ 中:
#include <iostream>
int main()
{
char a = 'a';
std::cout << "Size of char : " << sizeof(a) << "
";
std::cout << "Size of char : " << sizeof('a') << "
";
return 0;
}
输出:
Size of char : 1
Size of char : 1
为什么 sizeof('a')
在 C 和 C++ 中返回不同的值?
Why the sizeof('a')
returns different values in C and C++?
推荐答案
在 C 中,像 'a'
这样的字符 constant 的类型实际上是一个 int
,大小为 4(或其他一些依赖于实现的值).在 C++ 中,类型是 char
,大小为 1.这是两种语言之间的许多小差异之一.
In C, the type of a character constant like 'a'
is actually an int
, with size of 4 (or some other implementation-dependent value). In C++, the type is char
, with size of 1. This is one of many small differences between the two languages.
这篇关于C/C++ 中字符 ('a') 的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C/C++ 中字符 ('a') 的大小
基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04