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') 的大小
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
