4 ms·
Think about how this is compiled. In machine language there are no nested expressions, so the compiler will have to split the expression up. expression( ..
by jules 17y ago
Think about how this is compiled. In machine language there are no nested expressions, so the compiler will have to split the expression up.
expression( ... ++x ... )
will probably be translated to
x = x+1;
expression( ... x ... )
This is the simplest way to compile ++x:
1. put x=x+1 before the expression
2. replace ++x with x
So I think most languages would get 22.
But in languages where + is a function there's a good chance you get 21.
- 3ds 17y agoJava's result is 21 gcc says 22 and it gives you a warning, that this expression is illegal, we looked it up, because you cannot use a variable which is ++incremented more than once in the same expression.
- gizmo 17y agoSounds plausible, but I don't think it's true. Compilers don't magically filter assignments out of expressions. The compiler already has the parse tree (+ x (1+ x)), and the arguments are pushed on the stack in reverse order because that's consistent with function calls (in c++ when you were to overload operator+ nothing would change, I suspect). So first 1+ x is evaluated and the value of x is updated, and the number 22 is returned. Or to illustrate with a stack machine: PUSH X INC STORE X PUSH X ADD STORE Y But the whole discussion is still silly, because the whole deal is undefined in any sane language (and for good reason). Unless variables become immutable you can't really prevent this kind of ambiguity from occurring, so it's no big deal.
- jonsen 17y agoJava: "Regardless of their complexity, the meanings of expressions are allways well defined." That's why you can infer that y = 21 in Java. Would you call Java insane for that?