Reputation: 23
I was coding to find the prime number and extract the result as a boolean (true/false or 1/0) using the below code.
#include <iostream>
using namespace std;
bool isPrimeNumber(int n) {
int m, i;
m = n / 2;
for (i = 2; i < m; i++) {
if (n % i == 0) {
return true;
} else {
return false;
}
}
}
int main() {
cout << isPrimeNumber(33);
return 0;
}
(Here the result should be 0 since 67 is a prime number)
(I'm skipping negative numbers and 0,1, but I will add it later)
Then on line 9, it said "error: control reaches end of non-void function."
I tried to find the solution on the Internet, and of course, StackOverflow. But my code was still right and buildable.
I think it has something to do with treating warnings as errors (I changed it under recommendation as a beginner). But I don't wanna change it back since I'm still learning.
Do you have a way to solve this problem without changing my setup back to normal?
Upvotes: 1
Views: 140
Reputation: 474
When n is odd you get the error :
error: control reaches end of non-void function.
You're checking divisibility of n by only one value i=2. You have to check for each value of i from 2 to m.
Return false after iteration of for loop is completed.
Change your isPrimeNumber()
function as below:-
bool isPrimeNumber(int n){
int m,i;
m = n/2;
for (i=2;i<m;i++){
if (n % i == 0){
return true;
}
}
return false;
}
Upvotes: 2