# C++ Boolean variable - clarity sought

1. Apr 17, 2015

### Lord Anoobis

This is an example from a study guide I'm using at the moment in learning C++.
Code (Text):

//Test whether a number is prime
#include <iostream>
using namespace std;
int main ()
{
int x, y;
bool factorFound = false;

cout << "Enter a positive integer: ";
cin >> y;
x = 2;

while (x != y && !factorFound)
{
if (y % x ==0)
factorFound = true;
x++;
}
if ( x == y)
cout << y << " is prime." << endl;
else
cout << y << " is not prime." << endl;

return 0;
}
I hope this doesn't end up looking awful. Anyway, the book is rather vague about happening here. Does the variable factorFound represent a Boolean false when initialised? Also, I don't see how it works in the condition in the while loop. How does !factorFound affect things? I understand how the program works as a whole, but these details elude me. In the dark and on need of light to be shed on this.

2. Apr 17, 2015

### rootone

Yes, the variable factorFound is a Boolean value and it is initialised as false.
It only changes state to true, when within the loop, your input value is found to be divisible by an integer (x), which is your loop counter.
When this happens this will cause the loop to end. with a value of x which is less then y.
After the loop finishes, it tests if x is equal to y, and if it is this means the loop continued to completion without any divisible integer being found,
hence your input was a prime number.

3. Apr 17, 2015

### Staff: Mentor

On Visual Studio 2013, a bool variable is 1 byte. The MSDN documentation says that the size of this type is unspecified, but using the sizeof operator on a variable of type bool evaluated to 1.

Uninitialized, its value is 0xCC. When set to false, its value is 0x00, and when set to true, its value is 0x01.

4. Apr 17, 2015

### Lord Anoobis

So basically, the loop condition becomes false when factorFound becomes true within the loop?

5. Apr 17, 2015

### rootone

Yes.

6. Apr 17, 2015

### Lord Anoobis

What you have said seems to be a bit beyond my current capabilities. I'll have to look into it.

7. Apr 17, 2015

### Lord Anoobis

Got it. That was causing a bit of a headache. Thanks.

8. Apr 18, 2015

### Staff: Mentor

The ! ("not") operator reverses a boolean value. If factorFound is true, then !factorFound is false. If factorFound is false, then !factorFound is true.

9. Apr 21, 2015

### Svein

I do not like this part of the program.
1. Since factorFound is true whenever a divisor is found, I do not see why you do not use it in the printing routine (if (factorFound) /* not prime */... )
2. You are doing a lot of unnecessary comparisons, since no factor can be greater than the square root of y.