Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
    
see also: Why are nested loops considered bad practice? –  gnat Dec 6 '13 at 11:31

5 Answers 5

up vote 12 down vote accepted

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.

share|improve this answer
1  
+1 for the example you cite –  GlenH7 Feb 4 '13 at 15:00
1  
If you worry about performance, you should advise your compiler to inline the function. –  Martin Schröder Feb 5 '13 at 12:34

There are advantages and disadvantages to both approaches. Which approach you prefer should depend upon your team's style and guidelines. For now, since your professor doesn't like a particular method, you shouldn't use it for the code you submit.

But don't get too hung up on either approach.

Calling a function from within the outer loop simplifies the task of analyzing the outer loop. But it also increases the overhead from the stack creation / deletion with a large number of function calls. It can also be more difficult to code since shared variables between the loops will need to be passed and returned with each function call.

Nested loops are a little quicker to write. But they can drag out the length of the function. Longer functions tend to be more brittle, which makes maintenance more difficult. Longer functions are also more difficult to wrap your head around since they're ... longer. It's a bit obvious, but worth pointing out.

There's a lot of existing C code written with nested loops without additional function calls. So you'll see a lot of it in the wild. However, just because "it's always been done that way" doesn't necessarily mean it's the right way.

share|improve this answer

The advantage is that your main() is now simpler and easier to read (especially if the body of the inner loop is at all complicated).

It would be a disadvantage if the inner loop were very obvious, since it would then take slightly more effort to read something that should take almost no effort.

Do whatever results in more readable code.

share|improve this answer

For different scenarios different approaches are considered. When we want to submit a code which is easy to understand by the teacher or any other friend then we should definitely avoid using nested loops as it becomes difficult for the checker to trace the calls for all the variables one by one. But if there is no such case then there is no harm in using the nested loops as there is not such any change in the complexities. Making additional functional calls just increases the number of the activation records used for different functions and also the memory required for the current activation record pointer and the other pointers that point to the previous records of the functions increases.Thus in both the ways the memory increases but it is up to the programmer which approach to use.But the preferred one is to make functions for different purposes as it becomes easy for the programmer also to understand the code after if he/she reviews it after some time.

share|improve this answer

The more general advice is: watch out for deep levels of nesting. I've heard it called the "arrowhead" or "mountain range" anti-pattern, because that's what the code starts to look like. If you're nesting 2 levels for loops, then another level for if...then, and then if..thens inside the if...thens, the level of nesting can make the code really hard to follow.

  • I read an article where a team had huge maintenance problems with their code, so they implemented a policy of a maximum depth of nesting. Their bug rate dropped to almost nothing.

  • Someone famous once said, any code nested more than 3 layers deep is incomprehensible.

Hm. I can't find that quote now, but I did find a related article about nesting if...thens:

http://www.drdobbs.com/architecture-and-design/refactoring-deeply-nested-code/231500074

EDIT: here it is: "if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program."

https://www.kernel.org/doc/Documentation/CodingStyle

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.