On Mon, 6 Jun 2011 01:29:11 -0700 (PDT), "dr.oktopus"
<blindwilly@freeonline.zzn.com> wrote:
>Hello,
>walking an array is a common construct in programming.
>In C language, I see two common practises.
>
>1:
>
>for (p = array, pend = array + size ; p < pend ; ++p)
>/* do something */
>
>2:
>
>count = size;
>p = array;
>while (count--) {
>/* do something here */
>++p;
>}
>
>In complex contests, keeping a count variable could
>be more readable (IMO) than having a variable acting
>as a sentinel for the array bound (I'm speking of pieces
>of codes where array navigation is not from the start
>to the end, or inside Duff's devices, for example).
>My question is: is this code really inefficient than
>first approach (since it has to dec a variable every
>cycle, more than test it) or current cpus could handle a sort
>of decrement and test instr that do it all at the same time?
In ye olde days of yore the second form would have been more efficient
than the first. Decrement, increment, and test against zero are all
much simpler instructions, than the compare of two pointers, which
requires a subtraction. Many machines had a one instruction decrement
and test against zero. In these days with modern machines and modern
compilers it's almost certainly a wash. If there is a difference it
could be either way.
All of that said, I would write your second form like this:
for (count=size,p=array;count--;++p) {/* body */}