I've seen people say this a repeatedly when talking about "embedded" environments, but never understood why - won't it end up compiling to the same thing either way?
I've seen people say this a repeatedly when talking about "embedded" environments, but never understood why - won't it end up compiling to the same thing either way?
'a++' (postfix) and '++a' (prefix) have slightly different meanings in terms of return values. Postfix will return the value of 'a' before the increment, while prefix will return 'a' after the increment operation.
In a simple compiler, you would store the previous value of 'a' in the case of postfix in case you need to assign it. This results in a superfluous store instruction in most cases.
Of course, a smarter compiler could see the lack of assignment and throw away the store instruction during an optimization pass.
/* a = (b * 2) + 1 */
a = b; /* mov a, b */
a <<= 1; /* shl a, 1 */
a |= 1; /* or a, 1 */The difference in the two is that the latter has to produce the original value, presumably by keeping it in a temporary variable. A compiler which looks at all the code in a function when optimising, rather than just blindly emitting code for each individual operation, will see that the value is not needed, and delete the temporary.
I guess cc65 is a bit more basic. Compilers for more unusual embedded environments are often a bit more basic, hence the general advice for the embedded context.
I think you could probably fix the compiler for this trivial case in the time it takes you to write down the advice though.
If you mean "increment g" then write "++g"
If you mean "temp = g; increment g; return g" then write "g++"
It doesn't really matter that the compiler may optimize out the "temp". If you're writing "g++" you're indicating you want the value before it's been incremented.
g++;
++g;if(g++) {
//do something
}
Which obviously will do something if g was non-zero before incrementing it by one. It's a really poor way of writing code, but I have seen it done.
However, it's an altogether different situation to the one I wrote about, given that the value of the incrementing expression is specifically used in that case.
I keep meaning to test this in C++. I presume that it would for fundamental types, but wouldn't be able to be objects, because the side effects of that operation could be in another module. I use ++i for C++ iterators for that reason, and the habit tends to spill over to C.