请解释为什么会发生在第二行:
int i=5;
printf(" Before %d then operated %d and after %d", i, ++i, i); // Before 6 then operated 6 and after 5
printf("\n And now %d", i); //And now 6
就我所学到的,结果应该是在5之前然后操作6和之后6.我无法解释我是谁在学习..我是C的新手
在Borland C ++ 5和代码块中测试......
答案 0 :(得分:4)
函数参数的评估顺序是未指定的,由参数类型,被调用函数的calling convention,优化,体系结构和编译器决定。
来自c99标准:
6.5.2.2函数调用
功能指示符的评估顺序,实际 参数和实际参数中的子表达式是 未指定,但在实际调用之前有一个序列点。
只是为了增加一些经验(借鉴here) 以下代码:
int i=1;
printf("%d %d %d\n", i++, i++, i);
结果
2 1 3
- 在Linux.i686上使用g ++ 4.2.1
1 2 3
- 在Linux.i686上使用SunStudio C ++ 5.9
2 1 3
- 在SunOS.x86pc上使用g ++ 4.2.1
1 2 3
- 在SunOS.x86pc上使用SunStudio C ++ 5.9
1 2 3
- 在SunOS.sun4u上使用g ++ 4.2.1
1 2 3
- 在SunOS.sun4u上使用SunStudio C ++ 5.9
答案 1 :(得分:1)
您可能认为printf
中的评估顺序是从左到右。
这是错的!
未指定函数参数的评估顺序。
在您的特定示例中,订单似乎是从右到左。