Bey*_*rse 4 c stack-overflow termination
我最近几天前写了我的Grad学校入学考试,测试中出现了以下问题.
当使用任何正整数作为参数调用以下函数时,它是否会终止?它还打印什么?
void convert (int n)
{
if (n < 0)
printf ("%d", n);
else
{
convert (n/2);
printf ("%d", n%2);
}
}
Run Code Online (Sandbox Code Playgroud)
根据我的说法,因为控件永远不会到达if语句内部,并且因为printf语句放在else块下的函数调用之后,所以不会打印任何内容.n的值永远不会低于0,并且函数会一次又一次地调用自身,直到堆栈溢出.我的问题是代码是否因堆栈溢出而异常终止?
代码不会以正整数参数终止,因为n < 0永远不会满足基本条件.
递归调用convert使用参数调用它n / 2,作为整数除法,它将不可避免地达到零,但绝不会小于它.
例如,使用参数10:
call convert(10)
10 < 0 is false; enter the else branch
call convert(10 / 2)
5 < 0 is false; enter the else branch
call convert(5 / 2)
2 < 0 is false; enter the else branch
call convert(2 / 2)
1 < 0 is false; enter the else branch
call convert(1 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch
Run Code Online (Sandbox Code Playgroud)
它永远不会进入基础案例.