程序输出

Output of Program

#include<stdio.h>

int main() {
 short int i=20;
char c=97;
printf("%d,%d,%d",sizeof(i),sizeof(c),sizeof(c+i));
return 0;
}

假设 short int 的大小为 2,char 为 1,int 为 4B 好吧,如果我在机器上 运行 它给出 2,1,4 但是答案是 2,1,2

对于初学者来说,这个电话

printf("%d,%d,%d",sizeof(i),sizeof(c),sizeof(c+i));

有未定义的行为,因为使用了不正确的格式说明符。

它应该看起来像

printf("%zu,%zu,%zu",sizeof(i),sizeof(c),sizeof(c+i));

因为sizeof运算符求值的类型是size_t.

由于整数提升(作为 常用算术转换的一部分 ),表达式 c + i 的类型为 int.

来自 C 标准(6.3.1 算术操作数)

  1. ...If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.58) All other types are unchanged by the integer promotions.

和(6.5.6 加法运算符)

4 If both operands have arithmetic type, the usual arithmetic conversions are performed on them.

因此,如果类型 int 的对象的大小等于 4,则表达式 sizeof(c+i) 产生 4.