a = (a + b) - (b = a); C++ vs php

前端 未结 3 601
臣服心动
臣服心动 2021-01-05 21:11

I\'ve been looking around and found formula: a = (a + b) - (b = a) it is supposed to swap two variables (or objects in some cases). However I tested it with C++

3条回答
  •  孤城傲影
    2021-01-05 21:56

    For PHP:

    $a = 10;
    $b = 20;
    $a = ($a + $b) - ($b = $a);
    //executes like thus
    $a = (30) - ($b = $a);
    $a = (30) - ($b = $a = 10); //new $a still not computed, using older $a
    $a = (30) - (10);
    $a = 20;
    //then, $a=20 and $b = 10
    

    This is totally related to Operator Precedence, this might be same in C or might not, it depends on precedence if unexpected behavior not occur.

提交回复
热议问题