by Radim · 13y ago · 0 comments
EDIT: changed, I said decrement and meant increment.
for( i=LEN-1; i>=0; --i ) {...}
I've carried this into a lot of other languages, as it's equally readable to the alternatives, when ordering isn't important. In (mainly older) optimised code where ordering is important, you'll often still see this, with a second incrementing variable so that the exit condition retains the compare to zero (avoiding a variable comparison); although that part is separate from the use of the pre-decrement.
I'm not sure if either of these make much difference with modern CPUs and compilers. Certainly not worth worrying about for the most part.
It's untrue that this idiom started with C++. This style is preferred by K&R, which predates optimising compilers. Since then it's use among C programmers has probably been force of habit, but it is definitely idiomatic. It's use in K&R makes it about as idiomatic as it is possible to be.
for (i = 0; i < n; i++)
...
This is the kind of code I run across most commonly (almost exclusively) in pre-1990s C. It's also the style used in the old Unix sources. For example, take a look at the source code to 'nohup' or 'mount' from 5th Edition Unix, 1974: http://minnie.tuhs.org/cgi-bin/utree.pl?file=V5/usr/source/s... http://minnie.tuhs.org/cgi-bin/utree.pl?file=V5/usr/source/s...They do also use predecrement/preincrement, but only in assignments or comparisons, where it actually semantically matters that the increment/decrement is "pre":
while(*--np == '/')
*np = '\0';
In contexts where it doesn't matter, like the 3rd clause of a for loop, or just incrementing a variable as a standalone operation, they always default to x++.That trend didn't last very long, though.