View previous topic :: View next topic |
Author |
Message |
jecottrell
Joined: 16 Jan 2005 Posts: 559 Location: Tucson, AZ
|
Reading an Array in Reverse |
Posted: Thu Mar 22, 2007 9:54 am |
|
|
Hello All,
I don't know if I've been staring at this too long but I can't figure it out.
I'd like to be able to read an array in reverse order (from highest index to 0). But I can't think of what conditional operators to use to prevent rolling over on an int8 typed index....
Code: |
for(i = current_index; i >= 0; i--)
{
}
|
With an index typed as int8 it will rollover to 255 and keep on going. Is the only way to handle the problem with signed indexes? Or is there a nifty way to do it?
Thanks,
John |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1907
|
|
Posted: Thu Mar 22, 2007 10:13 am |
|
|
If the array has less than 256 elements, this should work:
Code: | for (i = current_index; i < 0xff; i--) {
.......
} |
i will start at whatever current_index is, and keep decrementing until it rolls over to 255 (0xff). As soon as it does, i is no longer less than 0xff and the for loop should exit. |
|
|
jecottrell
Joined: 16 Jan 2005 Posts: 559 Location: Tucson, AZ
|
|
Posted: Thu Mar 22, 2007 11:05 am |
|
|
Well duhhhhh......
Thanks! |
|
|
kevcon
Joined: 21 Feb 2007 Posts: 142 Location: Michigan, USA
|
|
Posted: Thu Mar 22, 2007 11:17 am |
|
|
You could do it this way too.
Code: |
do {
// ....your code here
}while( --i != 255 );
|
|
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Thu Mar 22, 2007 12:44 pm |
|
|
Or another solution that works for all data types (int8, int16, etc)
Code: | do
{
// ....your code here
} while (i-- != 0); // note that i-- is a post-increment, it will exit the loop with i == -1. |
|
|
|
jecottrell
Joined: 16 Jan 2005 Posts: 559 Location: Tucson, AZ
|
|
Posted: Thu Mar 22, 2007 2:31 pm |
|
|
Ahhhhh.......
That's exactly what I was looking for.
Thanks! |
|
|
|