Warning: The address will always evaluate as true.

My code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
bool checkPrime(int B)
{
for(int i = 2; (i*i) <= B; ++i)
      { 
      return true;
      if(B % i == 0)
      {
          return false;
          break;
      }
      }
}

int main()
{
	int response;
	cout << "Please enter a number between 1 and 50.";
	cin >> response;
	if (checkInput(response))
	{
	checkPrime(response);
	printResult(checkPrime);
	}
} 


I didn't include checkInput() and printResult() because both should work, but for some reason checkPrime() always evaluates as true, but if I make a separate program not using a separate bool function and just the put the function into int main() it works. Why does it always evaluate as true? Or could it be something in another function that causes it?
Last edited on
1
2
3
4
5
6
bool checkPrime(int B)
{
  for(int i = 2; (i*i) <= B; ++i)
 {
    return true;
     ....


The first thing the for loop does is return true;
Let's use code tags, that means wrapping [code] and [/code] around your code
1
2
3
4
5
6
7
8
9
10
11
12
bool checkPrime(int B)
{
    for(int i = 2; (i*i) <= B; ++i)
    { 
        return true;
        if(B % i == 0)
        {
            return false;
            break;
        }
    }
}


As soon as you go into your for loop, you return true. It's the very first thing you do inside the for loop. Your other code is never even reached.

I would move the return statement to after your for loop.
Ahhh okay so once it returns it doesn't execute anymore.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
bool checkPrime(int B)
{
	 for(int i = 2; (i*i) <= B; ++i)
        {
                 if(B % i == 0)
                 {
                          return false;
                 }
        }
    return true;
}

int main()
{
	int response;
	cout << "Please enter a number between 1 and 50.";
	cin >> response;
	if (checkInput(response))
	      {
	      checkPrime(response);
	      printResult(checkPrime);
	      }
}


For some reason it is still always returning true.
Last edited on
checkPrime(response);
You are throwing away the result. You have no idea if it always returns true or not, because you aren't checking the return.


printResult(checkPrime);
This is nonsensical.
Last edited on
Ohh I see, so it doesn't stay.
Last edited on
Ahhh got it now! Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
	int response;
	cout << "Please enter a number between 1 and 50.";
	cin >> response;
	if (checkInput(response))
	{
	if (checkPrime(response))
	printResult();
	else
	cout << "This number is not prime.";
	}
	}


Changed printResult to only cout that it's prime rather than be a conditional based on checkPrime, didn't realize the result didn't stay either.
Last edited on
Topic archived. No new replies allowed.