为什么 sizeof(char + char) 返回 4? [英] Why does sizeof(char + char) return 4?
问题描述
char a, b;
printf("%d", sizeof(a+b));
printf 会在屏幕上写什么?
What will printf write to the screen?
我以为因为sizeof(char)=1,所以sizeof(a+b)也会是1,结果竟然是4.我不明白,为什么加2会写4字符?
I thought because sizeof(char)=1, that sizeof(a+b) will be also 1, but it turned out to be 4. I don't understand this, why does it write 4 if we are adding two chars?
推荐答案
在 C 语言中,几乎所有算术运算符的操作数都经过隐式转换,称为 通常的算术转换,在这种情况下,整数促销.char
类型的操作数被提升为 int
类型,实际加法是在 int
(或 unsigned int
,取决于该平台上 char
的属性).所以你的 a + b
实际上被解释为 (int) a + (int) b
.结果的类型为 int
并且 sizeof(int)
在您的平台上显然是 4.那 4 就是你所看到的.
In C language operands of almost all arithmetic operators are subjected to implicit conversions called usual arithmetic conversions or, in this case, integer promotions. Operands of type char
are promoted to type int
and the actual addition is performed within the domain of int
(or unsigned int
, depending on the properties of char
on that platform). So your a + b
is actually interpreted as (int) a + (int) b
. The result has type int
and sizeof(int)
is apparently 4 on your platform. That 4 is what you see.
并且不要使用%d
来printf
sizeof
的结果.sizeof
的结果类型为 size_t
,而 %d
需要一个 int
参数.所以,要么使用正确的格式说明符
And don't use %d
to printf
the result of sizeof
. The result of sizeof
has type size_t
, while %d
requires an int
argument. So, either use the proper format specifier
printf("%zu
", sizeof(a+b));
或者如果你确定它适合的话,至少要转换它
or at least cast the argument if you are sure it fits
printf("%d
", (int) sizeof(a+b));
这篇关于为什么 sizeof(char + char) 返回 4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!