hello
hello

Reputation: 1229

Two index increment in for loop

While reading a text on loop analysis, I came across the following linear search routine to return the maximum value in an array:

template <class otype>
int location_of_max (const otype a[], int first, int last)
{
    int max_loc = first; 
    for (++first; first <= last; ++first) {
        if (a[first] > a[max_loc]) {
            max_loc = first;
        }
    }

   return max_loc;
}

Having two increments ++first in the same loop condition is a bit confusing. Is there a reason for this?

Upvotes: 2

Views: 792

Answers (3)

Pemdas
Pemdas

Reputation: 543

Take a look at what it is doing.

  1. Initialize max_loc to the first index.

The format of a for loop is ( init; condition; increment ).

At this point there is no need to check if a[first] > a[max_loc] because first == max_loc, so as part of init first is pre-incremented to the next index. This step is only executed once. The second increment happen on every iteration of the loop.

Upvotes: 2

Arif Burhan
Arif Burhan

Reputation: 505

The first clause in the for statement is just a starting value, executed only once, before the block executes.

The third clause is executed at the end of each block iteration, and just before the condition - second clause - is evaluated.

Upvotes: -3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

The code compares two elements on each loop.

The initial loop declaration statement is advancing the "start" iterator to the second array position, because the "reference" element (a[max_loc]) begins life as the first element.

This avoids one unnecessary and meaningless comparison (i.e. a[max_loc] > a[max_loc]).

Upvotes: 6

Related Questions