Here’s another short side-musing about C…
At my previous job, I did embedded programming on TI MSP430, PowerPC and Renesas processors. We were in the process of moving to a new system based on ARM architecture. It was during this time that I went from being part of a tiny local team to being part a much larger group spread out around the world.
But I digress.
On this team were some great minds, and one of them produced a document listing a bunch of optimizations we could do in our code to reduce size and/or improve speed. I wish I had a copy of it as it would be fun to discuss the suggestions here and get some feedback. But for today, I’ll bring up one that was just brought up by a coworker at my current job.
var++ versus ++var
I am very used to writing (and seeing) variable increments written like this:
Is it called a post increment, I believe. There is another version called pre-increment that looks like this:
By themselves, the result appears the same. For example:
int i; i = 0; printf("i = %d\n", i); i++; printf("i = %d\n", i);
That would print 0, then i++ would increment it, then it would print 1.
int i; i = 0; printf("i = %d\n", i); ++i; printf("i = %d\n", i);
That would print 0, then ++i would increment it, then it would print 1.
The reason there is pre and post is for situations where you want to check something at the same time you increment it. If you use “i++” in a check…
i = 0; if (i++ == 1) printf("This will NOT be printed.\n");
…it checks the value of “i” , then increments it after the check (post increment, see?). But if you go the other way:
i = 0; if (++i == 1) printf("This WILL be printed.\n");
…it increments “i” first, then checks the new value of i.
Behind the scenes, “i++” has to do more work since it has to retain the original value of i for the compare. I think a post-increment might look something like this:
i = 0; // SET i TO 0 if ( i++ // SAVE VALUE OF i AS TEMP_i // INCREMENT i == 1) // COMPARE TEMP_i TO 1
And a pre-increment might look like this:
i = 0; // SET i TO 0 if ( ++i // INCREMENT i == 1) // COMPARE i TO 1
If all you are JUST wanting to increment (or decrement) a variable, it might make sense to always use the pre-increment version (“++i”) so the extra “save this value for later” code is not produced.
BUT, a good compiler optimizer should be able to see that nothing cares about that temporary value and just discard it rather than building it in to your binary.
With a good optimizer, it shouldn’t make any difference. But perhaps it’s better to write it like you mean it since “if (i++ …” means something different than “if (++i …”.
But geez, after twenty years of writing “i++” it sure would be hard to switch.
Does it matter? What if I am writing for an old pre-ANSI K&R compiler?