8
iamrp
6y

What is the result of i == (i = 2) ?

Want to add something ??

Source : https://stackoverflow.com/questions...

Comments
  • 9
    In C, it's undefined for good reasons. First, you don't eat where you shit because that would be indecent.

    Second, there are CPUs with interleaving, I remember specifically 56k. You write some value, but if you read back right in the following cycle, you will get the value from before the write. Only one cycle later, you get the value that you have written. That reflects into C in form of sequence points, which are absent in this expression.
  • 4
    Java: false
    C: undefined
    PHP: true
    JS: false

    I could keep going...

    It depends on language, and how it handles the operations and assignments.
  • 3
    @xaero
    I think it’s just one of those issues of languages being slightly different in the way they handle assignments and order of operations.

    PHP is a special breed for this scenario as I=2 will be assigned without I being declared prior and following the order of operations Of Right to Left, the assignment is made before the evaluation of I == 2.

    Other languages require I to be predefined before being used, so they’ll return false or have errors of assignment without declaration.
  • 4
    @xaero the evaluation result of (i = 2) is 2. However, C does not prescribe the order of evaluation. So it is free to first take the leftmost i, which may be anything, and then do the rest. Or the other way around. It is even free to optimise the complete code path away because it's undefined behaviour.

    Edit: i has to be declared first in C because otherwise, the code won't compile, that's why the PHP way to generate the variable on the fly is not possible.
  • 1
    @Fast-Nop how could it optimize this away? UB is confusing to me... And in the case of pipelined memory access, wouldn't there be nops inserted by a compiler (or reordering) when necessary? Maybe I'm overestimating the C spec
  • 1
    @beegC0de because undefined behaviour means exactly that - the C compiler is free to do anything. The optimisation is only bound to give the same observable result for code that doesn't contain UB.

    In case of pipelined access, the compiler would insert other instructions if there is a sequence point in-between, like in:
    i = 2;
    if (i == 2) {}
    (Though the whole if-comparison would be optimised away to always true anyway, unless i is volatile of course.)
Add Comment