Programming Practices – Declaring Functions to Avoid Explicit Nested Loops

code-qualityloopsprogramming practices

My programming professor has told me that it is a good programming practice (at least in C/C++) to declare a function with the inner loop when nesting loops (not for loops, since when, i.e. looping through a multidimensional array this is very intuitive). For example, if I write

int main()
{
    while (cond1)
    {
        // ...(1)...
        while (cond2)
        {
            // ...(2)...
        }
    }
}

then it is better:

type inner_loop(param)
{
    // ...(1)...

    while (cond2)
    {
        // ...(2)...
    }
}

int main()
{
    while (cond1)
    {
        inner_loop(param);
    }
}

What improvements do imply this method? Is there any case in which this way of programming nested loops can be counterproductive? Thanks in advance.

Best Answer

It adds a lot of readability at the expense of a little function call overhead, assuming you choose a better name than inner_loop. Unless you truly need every ounce of performance, there aren't many situations where it isn't advisable.

One thing to take note is that it hides the complexity of your algorithm. In general, this is a good thing. However, I once saw similar nested loops in functions create an O(n^6) function out of what should be O(n) or better, simply because maintainers way down the road didn't notice the nested loops when they were working on the outer layers.

Related Topic