c - 栈溢出异常终止

标签 c stack-overflow termination

我最近几天前写了我的研究生入学考试,考试中出现了以下问题。
当以任何正整数作为参数调用以下函数时,它会终止吗?它还打印任何东西吗?

void convert (int n) 
{
  if (n < 0)
    printf ("%d", n);
  else 
  {
    convert (n/2);
    printf ("%d", n%2);
  }
}

根据我的说法,不会打印任何内容,因为控件永远不会到达 if 语句内部,而且 printf 语句位于 else block 下的函数调用之后。 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

它永远不会进入基本情况。

关于c - 栈溢出异常终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54596837/

相关文章:

java - 通用可比较合并排序算法的 Stackoverflow 错误

Android - 计算器错误

C# 堆栈溢出

C# 问题 : program terminates itself when it shouldn't

c - 从 C 中的 *char[] 变量获取第一个字符

c - 如何用c编译汇编语言

c - 如何检查我的 C 代码使用的内存?

c - 将一个 Char* 映射到两个整数

coq - 任何额外的公理都能使 Coq Turing 完备吗?

cocoa - 观察cocoa应用程序中其他应用程序退出或突然终止