[英]About printf function and postfix increment operator (i++) in while loop. I want to know about procedure of the printf function
我想了解带有后缀增量运算符的“printf”函数的过程。
我调试了这些代码,发现每个 'printf' 函数在 while 循环结束后都处于活动状态。
我预计第二个 while 循环的结果是这样的
0 x 0 = 0
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
但这是错误的
我想知道参数的流程以及为什么打印出这样的结果。 ;(
抱歉我的英语不好,希望你们帮我解决这个问题。 谢谢你。
#include<stdio.h>
int main(void)
{
int num1 = 0, num2 = 0;
//test while and postfix increment operator
//first while
while (num1 < 30)
{
printf("%d x %d = %d\n", num1++, num2++, num1 * num2);
//the results
//0 x 0 = 1
//1 x 1 = 4
//2 x 2 = 9
//3 x 3 = 16 ...
//the procedure of the printf function is from left to right?
//the flow of arguments is from left to right
}
//reset
num1 = 0, num2 = 0;
printf("\n");
//second while
while(num1 < 30)
{
printf("%d x %d = %d\n", num1, num2, (num1++) * (num2++));
//the results
//1 x 1 = 0
//2 x 2 = 1
//3 x 3 = 4
//4 x 4 = 9...
//the procedure of the printf function is from right to left?
//the flow of arguments is from right to left
//...why..?
}
return 0;
}
这个问题有几个重复; 你遇到了不太明显的问题。
问题是这样的:
6.5 表达式C 2011 在线选秀
...
2 如果对标量对象的副作用相对于对同一标量对象的不同副作用或使用同一标量对象的值进行的值计算而言是未排序的,则行为未定义。 如果一个表达式的子表达式有多个允许的排序,并且在任何排序中出现这种未排序的副作用,则行为是未定义的。 84)
在printf
调用中,表达式num1++
和num2++
有副作用 - 它们更改存储在这些变量中的值。 但是,您还尝试在没有中间序列点的情况下在值计算 ( num1 * num2
) 中使用这些变量 - 程序执行中的一个点,其中++
副作用已应用于num1
和num2
。 C 不要求从左到右计算函数参数,也不要求在计算后立即应用++
运算符的副作用。
该行为被明确称为未定义- 编译器和运行时环境都不需要以任何特定方式处理这种情况。
要完成您想要的操作,您需要将num1
和num2
的更新分开:
while ( num1 < 30 ) { printf( "%dx %d = %d\\n", num1, num2, num1 * num2 ); num1++; num2++; }
或者,您可以将其重写为for
循环,如下所示:
for ( num1 = 0, num2 = 0; num1 < 30; num1++, num2++ ) printf( "%dx %d = %d\\n", num1, num2, num1 * num2 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.