C/C++ 中字符 ('a') 的大小 [英] Size of character ('a') in C/C++

查看:84
本文介绍了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') 的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆