carl said:
Interesting, I thought the two did produce different code, isn't this
true:
prefix op {
x = x + 1;
return x;
}
postfix op {
int tmp = x;
x = x + 1;
return tmp;
}
What does 'void context' mean and does this change the above code?
I'm new to this and would like to know whether I just wasted loads of
time changing my postfix to prefix in a futile attempt at optimisation!
A "void context" is a context in which an expression is evaluated only
for its side effects, with the actual result of the expression being
ignored.
"i++" yields the (previous) value of i; as a side effect, i is incremented.
"++i" yields the value of i+1; as a side effect, i is incremented.
If the result is used as part of a larger expression, such as
x = i++;
the compiler may need to use a temporary to hold the previous value of
i -- but since "x = i++;" and "x = ++i;" aren't semantically
equivalent, there's not much point in comparing their performance.
If the result is discarded, as in a statement context:
i++;
++i;
the expression *theoretically* yields the same result as it would in
any other context, but any decent compiler will be smart enough to
take advantage of the fact that the result isn't used. If a compiler
generated significantly different code for "i++;" and "++i;", it's
probably a bug.
Note that the first and third expression in a "for" statement also
provide a void context, so
for (i = 0; i < 10; i++) { ... }
and
for (i = 0; i < 10; ++i) { ... }
are equivalent -- and many programmers won't even notice the
difference when reading the code.