简体   繁体   中英

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; }

It's because there is no base case in your recursive function. The detector() function will keep on giving out an infinite value as there is no base case to terminate the recursive call in the detector() function.

detector() is evaluated regardless of the value of n % i != 0 && n != ++i – there is no short-circuiting in multiplication.

Also, since the evaluation order of operands in arithmetic is unspecified, detector() might happen before anything else, leaving both i and j unmodified.

The simplest fix is to use logical operators instead of arithmetic:

bool detector() {
    return (n % j != 0 && n == ++j) || (n % i != 0 && n != ++i && detector());
}

You should also change main , which suffers from the same lack of short-circuiting:

std::cout << n == 2 || n == 3 || (n > 3 && detector());

I would also rewrite the code to not use global variables.
Globals are bad for you, but globals and recursion is even worse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM