Multiple assignment on one line not working as expected

后端 未结 3 1599

I\'m trying to swap two ints - x and y in the example, and do it in one line without a library function.

So I started with thi

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-17 08:44

    Let's try to expand your last expression.

    It evaluates to,

    x = x^(y = y^ (x = x^y));
    

    Note that expressions are evaluated from left to right,

    it becomes,

    x = 4 ^ (y = 3 ^ (x = 4 ^ 3));
    

    Now, the problem has become obvious. Right?

    Edit:

    To clear come confusion, let me try to explain what I mean by evaluating from left to right.

    int i = 1;
    s = i + (i = 2) + i;
    

    Now, the expression will evaluate to,

    s = 1 +    2    + 2;
    

    Notice that i on the left of assignment was 1, but on the right of assignment (and on the assigment) was evaluated to 2, because the evaluation is from left to right, when it came to the 2nd and 3rd part of the expression, is value was 2.

提交回复
热议问题