This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
                                
                                    (14个回答)
                                
                        
                                2年前关闭。
            
                    
有3个循环,最后一个循环的行为不符合预期。
循环2和循环3是错误的代码样式。他们在这里只是为了示范。问题是为什么循环3中的printf()提供意外的输出,而循环2中的printf()提供预期的结果?是因为编译器还是因为printf函数导致此错误?是否有任何文件解释在某些情况下编译器或某些函数的行为,因此我可以寻找将来的问题。

int main(void){

int mat1[3][4] = {4,5,0,3,0,0,1,2,0,0,0,6};

//****************** Output 1 ***********************************************

    for(int i=0; i<3;i++)
        for(int j=0;j<4;j++){
            printf("%d, ", mat1[i][j]);
            if(j==3)printf("\n");
        }


    /*   Expected output 1:

        4 5 0 3
        0 0 1 2
        0 0 0 6
    */

    printf("\n\n");

//******************* Output 2 ************************************************

    for(int i=0; i<3;i++)
        for(int j=0;j<4;j+=4)

            printf("\n%d, %d, %d, %d", mat1[i][j+0],mat1[i][j+1],mat1[i][j+2],mat1[i][j+3]);



    /*  Expected output 2:

        4 5 0 3
        0 0 1 2
        0 0 0 6
    */

    printf("\n\n");

//********************* Output 3 **********************************************

    for(int i=0; i<3;i++)
        for(int j=0;j<4;j)

            printf("\n%d, %d, %d, %d", mat1[i][j++],mat1[i][j++],mat1[i][j++],mat1[i][j++]);


    /*  Unexpected output 3:

        3 0 5 4
        2 1 0 0
        6 0 0 0
    */

}

最佳答案

    printf("\n%d, %d, %d, %d", mat1[i][j++],mat1[i][j++],mat1[i][j++],mat1[i][j++]);


那是非常糟糕的编码风格,但是发生的事情是printf在将j打印出来之前从右到左评估j。因此,这就是为什么第一个mat1 [i] [j ++] j为3,第二个为2,依此类推,直到最后一个mat1 [i] [j ++]的j为0。

关于c - 循环3中的printf()函数给出了意外的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51487678/

10-12 15:01
查看更多