问题描述
我在查看。我不能完全理解给出的解释,所以我写了一个程序:
#include< stdio.h>
int main()
{
char ch ='a';
printf(sizeof(ch):%d\\\
,sizeof(ch));
printf(sizeof(\'a\'):%d\\\
,sizeof('a'));
printf(sizeof(\a \):%d\\\
,sizeof(a));
printf(sizeof(char):%d\\\
,sizeof(char));
printf(sizeof(int):%d\\\
,sizeof(int));
return 0;
}
我使用gcc和g ++编译它们, p>
gcc:
sizeof(ch):1
sizeof ('a'):4
sizeof(a):2
sizeof(char):1
sizeof(int):4
g ++:
sizeof(ch):1
sizeof('a'):1
sizeof(a):2
sizeof(char):1
sizeof(int):4
g ++输出对我有意义,我对此没有任何疑问。在gcc中,需要有
sizeof('a')
与 sizeof(char)
不同吗?
也在C中,如果 char
和'a'
有不同的大小,这意味着当我们编写
char ch ='a';
在C中,字符常量例如'a'
code>有 int
,在C ++中是 char
。
关于最后一个问题,是的,
char ch ='a';
会导致 int
char
。
I was looking at the question Single quotes vs. double quotes in C or C++. I couldn't completely understand the explanation given so I wrote a program:
#include <stdio.h>
int main()
{
char ch = 'a';
printf("sizeof(ch) :%d\n", sizeof(ch));
printf("sizeof(\'a\') :%d\n", sizeof('a'));
printf("sizeof(\"a\") :%d\n", sizeof("a"));
printf("sizeof(char) :%d\n", sizeof(char));
printf("sizeof(int) :%d\n", sizeof(int));
return 0;
}
I compiled them using both gcc and g++ and these are my outputs:
gcc:
sizeof(ch) : 1
sizeof('a') : 4
sizeof("a") : 2
sizeof(char) : 1
sizeof(int) : 4
g++:
sizeof(ch) : 1
sizeof('a') : 1
sizeof("a") : 2
sizeof(char) : 1
sizeof(int) : 4
The g++ output makes sense to me and I don't have any doubt regarding that. In gcc, what is the need to have sizeof('a')
to be different from sizeof(char)
? Is there some actual reason behind it or is it just historical?
Also in C if char
and 'a'
have different size, does that mean that when we writechar ch = 'a';
, we are doing implicit type-conversion?
解决方案 In C, character constants such as 'a'
have type int
, in C++ it's char
.
Regarding the last question, yes,
char ch = 'a';
causes an implicit conversion of the int
to char
.
这篇关于单,双引号和sizeof('a')在C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!