为什么sizeof(char + char)返回4? [英] Why does sizeof(char + char) return 4?

查看:174
本文介绍了为什么sizeof(char + char)返回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。我不明白这就是为什么如果我们要添加两个字符,它为什么写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.

不要在 printf中使用%d 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\n", sizeof(a+b));

或至少在您确定合适的情况下使用参数

or at least cast the argument if you are sure it fits

printf("%d\n", (int) sizeof(a+b));

这篇关于为什么sizeof(char + char)返回4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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