[英]“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.