Why does c = ++(a+b) give compilation error?

dng picture dng · Jun 20, 2018 · Viewed 9.4k times · Source

After researching, I read that the increment operator requires the operand to have a modifiable data object: https://en.wikipedia.org/wiki/Increment_and_decrement_operators.

From this I guess that it gives compilation error because (a+b) is a temporary integer and so is not modifiable.

Is this understanding correct? This was my first time trying to research a problem so if there was something I should have looked for please advise.

Answer

Bathsheba picture Bathsheba · Jun 20, 2018

It's just a rule, that's all, and is possibly there to (1) make it easier to write C compilers and (2) nobody has convinced the C standards committee to relax it.

Informally speaking you can only write ++foo if foo can appear on the left hand side of an assignment expression like foo = bar. Since you can't write a + b = bar, you can't write ++(a + b) either.

There's no real reason why a + b couldn't yield a temporary on which ++ can operate, and the result of that is the value of the expression ++(a + b).