Does anybody know the limit of nested for loops in C or C++? If there is a limit, what is the reason?

There is a limit and it is big from memory but i cant tell you off the top of my head. It is to do with the stacks heaps and the like. You really want to have that many nested loops that you are worried about a limit?

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.

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!

>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.

This question has already been answered. Start a new discussion instead.