C ++是否限制递归深度? [英] Does C++ limit recursion depth?

查看:949
本文介绍了C ++是否限制递归深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,有一个最大递归深度。似乎是因为Python是一个解释器,而不是一个编译器。 C ++有同样的概念吗?或者它只与RAM限制连接?

In Python there is a maximum recursion depth. Seems it is because Python is an interpreter, not a compiler. Does C++ have the same concept? Or it is connected only with RAM limit?

推荐答案

C ++中的限制是由于堆栈的最大大小。这通常比RAM的大小小几个数量级,但是仍然相当大。 (幸运的是,像字符串内容之类的大东西通常不在堆栈本身上。)

The limit in C++ is due to the maximum size of the stack. That's typically less than the size of RAM by quite a few orders of magnitude, but is still pretty large. (Luckily, large things like string contents are typically held not on the stack itself.)

堆栈限制通常可在操作系统级别。 (如果您在Unix上,请参阅 ulimit shell内置的文档。)此计算机(OSX)上的默认值为8 MB。

The stack limit is typically tunable at the OS level. (See the docs for the ulimit shell built-in if you're on Unix.) The default on this machine (OSX) is 8 MB.

当然,堆栈的大小本身并不完全有助于解决你可以递归的深度。要知道,您必须计算递归函数(也称为堆栈帧)的激活记录(或记录)的大小。最简单的方法(我知道)是使用一个反汇编器(大多数调试器的功能),并在每个函数的开始和结束读出堆栈指针调整的大小。这是凌乱。 (你可以通过其他方式工作 - 例如,计算两个调用中的变量指针之间的差异 - 但是它们甚至更糟糕,尤其是对于可移植代码。从反汇编中读取值更容易IMO。)

Of course, the size of the stack doesn't entirely help by itself when it comes to working out how deep you can recurse. To know that, you have to compute the size of the activation record (or records) of the recursive function (also called a stack frame). The easiest way to do that (that I know of) is to use a disassembler (a feature of most debuggers) and to read out the size of the stack pointer adjustments at the start and end of every function. Which is messy. (You can work it out other ways – for example, computing the difference between pointers to variables in two calls – but they're even nastier, especially for portable code. Reading the values out of the disassembly is easier IMO.)

这篇关于C ++是否限制递归深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆