Re: should every thing be zero indexed?
- From: Thad Smith <ThadSmith@xxxxxxx>
- Date: Mon, 02 May 2005 14:11:51 -0600
jorchi@xxxxxxxxx wrote:
>
> I have noticed that, when a programmer wants to do something for a
> certain number of times, they usually count with zero indexed
> variables. For example,
>
> /*To do 10 times*/
> for(i = 0; i < 10; i++)
> //stuff
>
> There is a logical reason why you should do this with arrays, because
> of pointer displacement, but is there any reason for doing this in
> other cases? I just don't know why a programmer would want his 4th
> iteration to be numbered 3, that can cause some logical problems when
> debugging.
Either 0- or 1- based counting will work, of course. I think the
reason that most loops are zero based is for consistency with
indexing, so the user doesn't have to wonder whether the counter is
0-based or 1-based if he always uses 0-based.
If you don't use the iteration variable, you are free to choose. If
you use the iteration variable, you probably want to make its value
correspond to its natural use:
int zbv; /* number of previous iterations (0-based) */
int obv; /* iteration number (1-based) */
> So, I think we should use
>
> for( i = 1; i <= 10; i++)
>
> which is not seen much. If I'm missing any optimization question here,
> or maybe processor speed on executing the different loops, or any other
> thing, I'd love to know it.
A zero-based counter may be slightly faster on some processors that
would have a clear instruction, but not a load literal instruction.
On the other hand, if you are not using the iteration variable, more
efficient code is probably produced by counting down, since many
processors will generate a status code by the decrement operation or
even have a decrement-and-skip-if-zero instruction:
for (i = 10; --i >= 0; )
or
for (i = 10+1; --i; )
or
i = 10;
do {
...
} while (--i)
The last form is more efficient for some processors I use.
Unless it really matters, I suggest using the form that is most easily
related to the problem domain and readable.
Thad
.
- Follow-Ups:
- Re: should every thing be zero indexed?
- From: Gerry Quinn
- Re: should every thing be zero indexed?
- References:
- should every thing be zero indexed?
- From: jorchi
- should every thing be zero indexed?
- Prev by Date: should every thing be zero indexed?
- Next by Date: Re: should every thing be zero indexed?
- Previous by thread: should every thing be zero indexed?
- Next by thread: Re: should every thing be zero indexed?
- Index(es):
Relevant Pages
|