如何测量调用堆栈的长度



最近有一个测试问题问"有多深";fact1的调用堆栈,其中n=5。这是代码:

int fact1(int n)
{
if (n == 1)
{
return 1
}
else {
return n * fact(n-1)
}
}

考试的答案是5,但我相信是4。我不认为第一次通话会计入通话次数。

实际上,每个函数调用都在调用堆栈中结束。

您的示例看起来像C;在C中,总是存在一个main函数;即使CCD_ 2函数也在调用堆栈上结束。

我认为没有办法检查C中的调用堆栈;尤其是因为编译器可以优化掉它想要的任何东西。例如,它可以优化尾部递归,然后调用堆栈会比您预期的更小。

在Python中,调用堆栈很容易检查;只要您想,只要抛出一个异常(例如assert(False)(,就可以使函数崩溃。然后程序将产生一个错误消息;堆栈轨迹";,包括堆栈上每个函数的列表。

以下是python中的堆栈跟踪示例:

def fact1(n):
assert(n != 1)
return n * fact1(n-1)
def main():
f = fact1(3)
print(f)
main()

输出:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in main
File "<stdin>", line 3, in fact1
File "<stdin>", line 3, in fact1
File "<stdin>", line 2, in fact1
AssertionError

还有另一个有趣的例子:

def print_even(n):
if (n <= 1):
print('yes' if n == 0 else 'no')
assert(False)
else:
print_odd(n-1)
def print_odd(n):
if (n <= 1):
print('yes' if n == 1 else 'no')
assert(False)
else:
print_even(n-1)
def main():
n = 5
print('Is {} even?'.format(n))
print_even(n)
main()

输出:

Is 5 even?
no
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in main
File "<stdin>", line 6, in print_even
File "<stdin>", line 6, in print_odd
File "<stdin>", line 6, in print_even
File "<stdin>", line 6, in print_odd
File "<stdin>", line 4, in print_even
AssertionError

最新更新