sizeof问题

来源:互联网 发布:淘宝怎么上架虚拟商品 编辑:程序博客网 时间:2024/05/21 17:33
#include <stdio.h>  int main()  {  int i;  i = 10;  printf("%d\n", i);  printf("%d\n", sizeof(i++);  printf("%d\n", i);  return 0;  }

这个程序输出什么?


一般人是这个程序会输出

10

4

11

但是却出人意外的输出了

10

4

10

这个问题实际上就是对于sizeof操作符的使用问题, sizeof不是函数,只是一种操作符,对于其后的表达式,根本不会进行计算的。sizeof当预处理看就行了,它后面括号里的东西,根本不求值,只根据C的一堆规则判断结果类型,然后返回结果类型的大小,,


C++标准:

5.3.3 sizeof
The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is anunevaluated operand (Clause 5), or a parenthesized type-id.”


也就是说,如果sizeof的操作数是一个表达式的话,这个表达式时不会被计算的。

更有甚者

#include <stdio.h>  int main()  {  int i;  i = 10;  printf("%d\n", i);  printf("%d\n", sizeof(i=5);  printf("%d\n", i);  return 0;  }



点击打开链接