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

c# c++ c
MusiGenesis picture MusiGenesis · Nov 9, 2008 · Viewed 148.6k times · Source

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
}

Answer

Rune picture Rune · Nov 9, 2008

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
}