简体   繁体   中英

Boolean function encounters with warning as "not all control paths return a value" or "control reaches end of non-void function"?

#include <iostream>
    using namespace std;

    bool isPrime(int);

   int main()
{
   int n;
   cout<<"Enter range to print Prime Numbers\n";
   cin >> n;
   // 1 to 10 - 2,3,5,7
   for(int i = 2;i<=n;i++){
     if(isPrime(i)){
        cout<<i<<", "; //if it is PN
    }
   }
   cout<<endl;
    return 0;
}

bool isPrime(int n) {
    int i;   
    for(i = 2;i<=n/2;i++){  //-n/2
        if(n % i == 0){
            return false;
            break;
        }
    }
    if(i > n/2){
        return true;
    }
}

Here bool function is used for whether an input number is prime or not and returning value at each conditional statement within it but still, there is an error of not returing value at all control paths???

If control reaches the if statement after the loop, then it is guaranteed that i > n/2 is true . However, the compiler does not know this and it sees that no value is returned if the condition is false as there is no else branch and no additional statements. The solution here is to directly return true after the loop; there is no need to check a condition that must be true.

A few additional improvements:

  • using namespace std; should be avoided . Instead, you could write using declarations for only the namespace members you actually need.
  • You can reduce the range of factors you check in the isPrime function by only going up to the square root of the input number.
  • Remove the break statement after return false; since it will never be reached.
#include <iostream>
using std::cout, std::cin, std::endl;
bool isPrime(int);
int main() {
    int n;
    cout << "Enter range to print Prime Numbers\n";
    cin >> n;
    for (int i = 2; i <= n; i++) {
        if (isPrime(i)) {
            cout << i << ", ";
        }
    }
    cout << endl;
    return 0;
}

bool isPrime(int n) {
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

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