Re: circular shift array



Chris Torek said:

In article <N_adnSlUjZ1NczPb4p2dnAA@xxxxxx>,
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> wrote:
An easier way [to deal with circular queues], which doesn't involve
any shifting at all, is to maintain an object whose purpose is to
store the index of the first item. Then you just process the array
as follows:

idx = head;
for(i = 0; i < n; i++)
{
if(idx++ == n) /* idx = (head + i) % n is shorter, but costlier */

I believe you mean "if (++idx == n)" here.

Er, kind of. What I really meant was:

proc(arr[idx]);
if(++idx == n)
{
idx = 0;
}

(The post-increment
version can be made to work by changing other values, but it is
then not equivalent to the "idx = (head + i) % n" method.)

Or, one could say:

idx = (head + i) % n; /* if (idx++ == n) is faster, but less
correct */

which suggests perhaps you are doing premature optimization. :-)

Well, it does avoid a division. Had I got it right, I think it would
have been a reasonable thing to do. :-)

<snip>

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
.



Relevant Pages

  • Re: circular shift array
    ... is to maintain an object whose purpose is to ... store the index of the first item. ... idx = head; ... Reading email is like searching for food in the garbage, ...
    (comp.lang.c)
  • Re: warning: format ?%s? expects type ?char *?, but argument 2 has type ?int?
    ... On Sep 14, 8:59 am, Richard Heathfield wrote: ... you should probably keep in mind that `fgets' will store a newline character in the string if it reads one and has room to store it. ...
    (comp.lang.c)
  • Re: the mystery of
    ... Richard Heathfield wrote: ... snip ... ... I wouldn't dream of using it for that purpose. ...
    (comp.lang.c)
  • Re: c without usin any graphics function
    ... In article, Richard Heathfield writes ... using a compiler written by Borland. ... Presumably he had a purpose in so doing, but I still don't know what ... and he has not seen fit to enlighten me. ...
    (comp.lang.c)
  • Re: File handling question
    ... Richard Heathfield wrote: ... You seem to be confused about the purpose of fopen. ... into main memory. ... Okay, ...
    (comp.lang.c)