![](/img/trans.png)
[英]“Recursive on All Control Paths” error when implementing factorial function
[英]Compiler displays “recursive on all control paths” but the function is equipped with a end case
#include <iostream> unsigned short n; unsigned short i = 2; unsigned short j = 2; bool detector() { return (n % j != 0 && n == ++j) * 1 + (n % i != 0 && n != ++i) * detector(); } int main() { std::cout << "enter a number greater than 1\n"; std::cin >> n; std::cout << (n == 2 || n == 3) * 1 + (n > 3) * detector(); return 0; }
这是因为递归 function 中没有基本情况。 detector()
function 将继续给出无限值,因为没有基本情况来终止detector()
function 中的递归调用。
无论n % i != 0 && n != ++i
的值如何,都会评估detector()
——乘法中没有短路。
此外,由于算术中操作数的评估顺序未指定, detector()
可能会在其他任何事情之前发生,而i
和j
都未修改。
最简单的解决方法是使用逻辑运算符而不是算术:
bool detector() {
return (n % j != 0 && n == ++j) || (n % i != 0 && n != ++i && detector());
}
您还应该更改main
,它同样缺乏短路:
std::cout << n == 2 || n == 3 || (n > 3 && detector());
我还将重写代码以不使用全局变量。
全局变量对你不利,但全局变量和递归更糟糕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.