在C / C字符('A')的尺寸++ [英] Size of character ('a') in C/C++

查看:119
本文介绍了在C / C字符('A')的尺寸++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是字符的C和C ++的大小?据我所知字符的大小是C和C ++ 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:

In C:

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

在C ++:

In C++:

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

没有惊喜,他们都给出了输出:字符的大小:1

No surprises, both of them gives the output : Size of char : 1

现在我们知道,字符重新psented为 $ P $'A''B''C'|,...所以我只是修改了上面的codeS这些:

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\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 ++不同的价值观?

Why the sizeof('a') returns different values in C and C++?

推荐答案

在C,一个字符类型的的如'A'实际上是一个 INT ,用4大小(或其他一些实现相关的值)。在C ++中,类型为字符,用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天全站免登陆