For loops - running method calls in the declaration

For loops are a key part of recursive code, allowing us to iterate over items in a vector, or perform actions a set number of times without repeating the lines of code. We all know how they can be applied and declared, however, something which may not be very well-known is the ability to call a function or other code in the 'declaration' of the for loop.

Declaring a for loop

A for loop contains three basic elements - the initialisation of the variable being used, the condition on which to terminate the loop, and the increment for the variable. A common example is:

1 for(int x = 0; x < myVector.size(); x++)

Where x is our control variable, we'll loop through the elements in our vector and increment x by one at the end of each loop.

Using this knowledge allows us to make use of the for loops declaration statement in additional ways that might commonly be used within the for loop itself. For example, you can declare a for loop to include a method call, like so:

1 for(int x = 0; x < myVector.size(); x++, myFunction())

Here, alongside our increment of x, we're also calling a function 'myFunction()' to be run at the end of each loop. Normally of course, you would put this at the end of your loop, which would have the same effect, but there are some possibilities where you might enjoy employing this - perhaps to save putting it into brackets (and saving all of 3 lines of code) or, perhaps rather more mean, you could use it to make your code slightly less readable (after all, no one will be expecting it) and frustrate people new to coding as they try to work out what's going on. Of course it's not just methods you could put there - anything which you want to run at the end of each loop can go there.

This post has been to highlight this little feature of the for loop which isn't easy to find elsewhere. And there is good reason for that - putting a function call inside the for loop declaration would render your code less-readable when you can put it into the loop itself (as part of the code or on its own if that's the only thing that loop would need to do). So use this at your discretion, just don't be surprised to get someone asking you what's going on later!

Leave a Reply

Your email address will not be published. Required fields are marked *