Why does this use of comma work in a expression but fail in a declaration?

后端 未结 3 779
独厮守ぢ
独厮守ぢ 2021-01-13 08:48

Am from high level OOP languages C# and Java and recently started scratching my head in C. I feel C a bit weird as equally as one feels JS is. So want to clarify below:

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 09:39

    i = 0,1,2; 
    

    This is assignment, which is equivalent to:

    (i = 0), 1, 2;
    

    The comma operator(which has the lowest precedence) evaluates all operands from left to right, first the assignment i = 0, then the expression 1 and 2 and throws the result away.

    The second example

    int i=0,1,2;  
    

    is initialization. Compare it with the legal initialization int i = 0, j = 0;.

    It works if you use:

    int i=(0,1,2); 
    

提交回复
热议问题