What's the best way to do a backwards loop in C/C#/C++?

c c# c++

Question

I need to move backwards through an array, so I have code like this:

for (int i = myArray.Length - 1; i >= 0; i--)
{
    // Do something
    myArray[i] = 42;
}

Is there a better way of doing this?

Update: I was hoping that maybe C# had some built-in mechanism for this like:

foreachbackwards (int i in myArray)
{
    // so easy
}

Update 2: There are better ways. Rune takes the prize with:

for (int i = myArray.Length; i-- > 0; )
{    
    //do something
}
//or
for (int i = myArray.Length; i --> 0; )
{
    // do something
}

which looks even better in regular C (thanks to Twotymz):

for (int i = lengthOfArray; i--; )
{    
    //do something
}
2
91
11/14/2008 3:33:19 AM

Accepted Answer

While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is

for (int i = myArray.Length; i --> 0; )
{
    //do something
}
132
11/10/2008 4:17:10 AM

Exper Answer

Looks good to me. If the indexer was unsigned (uint etc), you might have to take that into account. Call me lazy, but in that (unsigned) case, I might just use a counter-variable:

uint pos = arr.Length;
for(uint i = 0; i < arr.Length ; i++)
{
    arr[--pos] = 42;
}

(actually, even here you'd need to be careful of cases like arr.Length = uint.MaxValue... maybe a != somewhere... of course, that is a very unlikely case!)

4
11/9/2008 3:58:53 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon