c-关于while循环中的printf函数和后缀增量运算符(i++).我想知道printf函数的过程



我想了解使用后缀增量运算符的'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 = %dn", 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 = %dn", 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表达式

2 nbsp 如果标量对象上的副作用相对于其他副作用未排序在同一标量对象或上使用同一标量的值进行值计算对象,则行为未定义。如果表达式的子表达式,如果这样的非序列侧,则行为是未定义的任何订单都会产生影响84(
C 2011在线草案

printf调用中,表达式num1++num2++有副作用-它们会更改存储在这些变量中的值。然而,您也试图在值计算(num1 * num2(中使用这些变量,而不需要插入序列点——在程序执行中,++的副作用已应用于num1num2。C不要求函数参数从左到右求值,也不要求在求值后立即应用++运算符的副作用。

行为被显式调用为未定义-编译器和运行时环境都不需要以任何特定的方式处理这种情况。

为了实现您想要的,您需要将num1num2:的更新分开

while ( num1 < 30 )
{
printf( "%d x %d = %dn", num1, num2, num1 * num2 );
num1++;
num2++;
}

或者,您可以将其重写为for循环,如下所示:

for ( num1 = 0, num2 = 0; num1 < 30; num1++, num2++ )
printf( "%d x %d = %dn", num1, num2, num1 * num2 );

最新更新