chara,b; 
printf("%d",sizeof(a+b));

What will printf write to the screen?

printf写入屏幕的内容是什么?

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?

我认为因为sizeof(char)= 1,sizeof(a + b)也将是1,但结果是4.我不明白这一点,如果我们添加两个字符,为什么写4?

2 个解决方案

#1


12

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.

在C语言中,几乎所有算术运算符的操作数都受到称为常规算术转换的隐式转换,或者在这种情况下是整数提升。 char类型的操作数被提升为int类型,实际的添加是在int域内执行的(或unsigned int,具体取决于该平台上char的属性)。所以你的a + b实际上被解释为(int)a +(int)b。结果的类型为int,而sizeof(int)在您的平台上显然为4。那是你看到的4。

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

并且不要使用%d来printf sizeof的结果。 sizeof的结果是size_t类型,而%d需要int参数。因此,要么使用正确的格式说明符

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));

更多相关文章

  1. 在平台上获取,可移植,更大和更快(无符号)的整数类型
  2. js 不同类型var的boolean运算验证
  3. 输入类型=日期的日期显示为dd-mm-yyyy格式
  4. JavaScript数据类型的一些注意点(2)
  5. javascript中的属性类型
  6. 根据AngularJS中的条件制作输入类型文件[duplicate]
  7. JS数据类型(一)
  8. javascript 数据类型转换
  9. javascript的数据类型,以及javascript中类型检测

随机推荐

  1. Android 面试题7
  2. Android群英传第四章笔记·ListView使用
  3. Android 中文API (38) —— Spinner
  4. botoom tab + title bar
  5. TabLayout绑定Viewpager后不显示文字
  6. 对于Fragment的总结
  7. Android之通过shape.xml制作渐变背景色
  8. [Android Samples视频系列之ApiDemos] Ap
  9. Android(安卓)Studio 中文乱码问题
  10. android视图切换动画:ViewAnimator类及其