Understanding the output order of printf function

Understanding of printf function output rules

Background content

Note : The author has not studied the source code of printf, only analyzes the problem from the call result. If there is any improper understanding, please correct me.
I recently encountered an interesting phenomenon using the printf() function.

int j=0;
printf("[%x][%x][%x][%x]\n",j++,j++,j++,j++); //Result: [3] [2] [1] [0]

I originally thought that the output result was [0] [1] [2] [3], but I did not expect the result to be: [3] [2] [1] [0]. and,

printf("[%x] [%x] [%x] [%x]\n", j++, j=j+1, j++, j++); //[3] [4] [1] [0]

It turned out to be [3] [4] [1] [0].
So I wrote some test codes,

int \
j=0; printf("[%x] [%x] [%x] [%x]\n", /*row1*/j++, j++,   j++, j++); //[3] [2] [1] [0]
j=0; printf("[%x] [%x] [%x] [%x]\n", /*row2*/j,   j++,   j++, j++); //[3] [2] [1] [0]
j=0; printf("[%x] [%x] [%x] [%x]\n", /*row3*/j++, j++,   j,   j++); //[2] [1] [3] [0]
j=0; printf("[%x] [%x] [%x] [%x]\n", /*row4*/j++, j=j+1, j++, j++); //[3] [4] [1] [0]
j=0; printf("[%x] [%x] [%x] [%x]\n", /*row5*/j++, ++j,   j++, j++); //[3] [4] [1] [0]
j=0; printf("[%x] [%x] [%x] [%x]\n", /*row6*/j++, ++j,   j++, ++j); //[3] [4] [1] [4]
j=0; printf("[%x] [%x] [%x] [%x]\n", /*row7*/++j, ++j,   ++j, ++j); //[4] [4] [4] [4]

Understand the content

It can be seen from row1~row3 that the
printf() function first calculates the value of each expression from right to left , and then formats the output from left to right .

It can be seen from row1, row5, and row7 that the
j++ expression returns the value before incrementing. It may be that printf created a temporary variable (guess "a=j; j=j+1; return a;"), where the temporary variable a is saved ;
++j expression returns the incremented j, where j is saved;
row1:
=> j++, j++, j++, j++
=> 从右至左计算,返回临时变量tmp
=> step3(tmp3=3, j=4), step2(tmp2=2, j=3), step1(tmp1=1, j=2), step0(tmp0=0,j=1);
=> 从左至右输出(tmp3, tmp2, tmp1, tmp0)。
=> [3] [2] [1] [0]

row5:
=> j++, ++j, j++, j++
=> 从右至左计算,j++返回临时变量tmp,++j返回j
=> step3(tmp3=3, j=4), step2(j=3), step1(tmp1=1, j=2), step0(tmp0=0, j=1);
=> 从左至右输出(tmp3, j, tmp1, tmp0)。
=> [3] [4] [1] [0]

row7:
=> ++j, ++j, ++j, ++j
=> 从右至左计算,++j返回j
=> step3(j=4), step2(j=3), step1(j=2), step0(j=1);
=> 从左至右输出(j, j, j, j)。
=> [4] [4] [4] [4]

In the same way, j is returned at step2 of row4, and finally 4 is output.

Then,

int arr[5] = {
    
    0, 1, 2, 3, 4};
int *p = arr;
j=0; printf("[%x][%x][%x][%x]\n", p[j++], p[j++], p[j++], p[j++]);
j=0; printf("[%x][%x][%x][%x]\n", p[++j], p[++j], p[++j], p[++j]);
j=0; printf("[%x][%x][%x][%x]\n", p[j++], p[++j], p[j++], p[++j]);
p = arr;j=0; printf("[%x][%x][%x][%x]\n", *p++, *p++, *p++, *p++);
p = arr;j=0; printf("[%x][%x][%x][%x]\n", *++p, *++p, *++p, *++p);
p = arr;j=0; printf("[%x][%x][%x][%x]\n", *++p, *p++, *++p, *p++);

What will be the result of this code?

Guess you like

Origin blog.csdn.net/jimaofu0494/article/details/97271909