What is the value of
Stefan Tilkov mentioned that he was asked to predict the value of
i after the following code was evaluated:
i = 1; i += ++i + ++i;
Before I go on, what's your answer?
Most interestingly, the correct answer seems to be that the result is undefined in the C family of languages. That's because it features three assignments to
i in one statement, and you aren't supposed to have more than one assignment per variable. I find that very interesting! Essentially, C takes the position that if assignments are involved, you cannot define the result of an expression, only a statement. So if I were to ask you:
ihas the value one. What is the result of evaluating the expression
It seems like a little thing, but for me this is an extremely deep distinction between C and many other languages. There are many, many languages where each expression can be evaluated independently of other expressions in the same "statement." Of course, the value of bindings can be altered by whatever happens before an expression is evaluated, but the expression has a well-defined behaviour. Many languages go so far as to erase the distinction between statements and expressions: Everything's an expression. That makes it much easier to reason about expressions and statements, and much easier to build compilers, interpreters, and other tools.
I don't have some wonderful insight or suggestion to close with, just that I think the trend in language design is in the direction of everything being an expression and having them all be independent of each other. And I think such languages go a long way towards making "trick questions" like this go away.
There's no trick question if the language's semantics aren't tricky to begin with.
- Kestrels, Quirky Birds, and Hopeless Egocentricity and my other books.
- Cafe au Life, a CoffeeScript implementation of Bill Gosper's HashLife written in the Williams Style.
- Method Combinators, a CS/JS library for writing method decorators, simply and easily.