Nested For Loops
Does anybody know the limit of nested for loops in C or C++? If there is a limit, what is the reason?
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
If there is a built-in limit in the C++ language, then hell is frozen over. There are practical issues -- you don't want to run out of memory or with two billion nested loops, each having its own counter variable, but the restriction there isn't from nested for loops, it's from other externalities.
for (;;) {
for (;;) {
for(;;) {
... 2 billion times ...
for (;;) {
goto end;
}
... 2 billion times ...
}
}
end:
This should be valid C++ code, and if your compiler can handle it (good luck!), and handle it smartly (haha), it should have no memory usage at all.
Rashakil Fol
Super Senior Demiposter
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
ANSI C allows 15 levels of nesting but some compilers evem allow more
Thank you, that helps a lot! The problem came from Python that seems to balk at more then twenty levels of nesting. Much of the Python interpreter DLL is written in ANSI C.
The actual question came up on the Python Forum on DaniWeb. I assumed it might be related to the C compiler.
I still need to know what the nesting limits of the typical C++ compiler are. I am sure it's much less than the suggested 2 billion!
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
Rashakil Fol
Super Senior Demiposter
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
>Does anybody know the limit of nested for loops in C or C++?
15 levels in C89, 127 levels in C99 and 256 in C++ are the minimum limits. Any decent compiler should take the standard's advice and not impose arbitrary limits, so if you hit pretty much any implementation limit then either you're an awful programmer, you're trying to hit a limit, your compiler probably sucks, or your automated code generator has a bug. ;)
>If there is a limit, what is the reason?
The standard has to guarantee that certain programs will work. As such, it needs to set minimum limits on a lot of things to ensure that those programs will work. An implementation is free to increase the limits, but required to support the minimum levels.
>The problem came from Python that seems to balk at more then twenty levels of nesting.
But it has nothing to do with limits in C. Python developers made an active choice to limit static nesting to 20 levels for performance reasons. If you want more nesting, Python allows non-static nesting where you have nested loops, then a function with nested loops as the inner operation.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401