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

后端 未结 14 2698
终归单人心
终归单人心 2020-11-28 01:39

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] =          


        
14条回答
  •  半阙折子戏
    2020-11-28 02:01

    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!)

提交回复
热议问题