I’m having a hard time getting my head around the initialisation of bool.
Consider the program i wrote below. As it stands, it outputs the correct answer. However, if i change the first "false" to "true", it outputs the opposite answer! Why does it matter how the bool is initialized? Why doesn’t the compiler believe the statement "if (45 == x) what = true;"?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int main()
{
bool what(false);
int x(2);
if (45 == x) what = true;
if (what) cout << "The same!" << endl;
else cout << "Not the same" << endl;
}
There is code that might set the boolean to true, but there is no code that could ever set the boolean to false. Thus, the only way the boolean could ever be false is if it started that way and was never set to true.
Just to add on what LB said, an easy way to solve this that will ignore how the bool was initialised would be this:
1 2 3 4 5 6 7 8 9 10 11 12 13
bool what; //Initialise however you want
int x (2)
what = (x == 45);
//I put x == 45 not 45 == x because it is more natural to say if this number is equal to 45,
//rather than to say is 45 equal to the number.
//It implies that the term on the left is the one with an unknown value and
//the one on the right is the one that the unknown is being compared to.
if(what) {
std::cout << "The same!" << std::endl;
} else {
std::cout << "Not the same" << std::endl;
}
A single equals sign is assignment and changes the value of the object on the left to be the same as the value of the object on the right. The result of the expression is the object on the left.
A double equals sign is equality comparison - it compares the two values and returns true if they are the same and false otherwise.
#include <iostream>
usingnamespace std;
int main()
{
bool what = false;
int x = 2;
//Test 1
if (2 == x) what = true;
if (what) cout << "The same!" << endl;
else cout << "Not the same" << endl;
// Test 2
what = true;
if (2 == x) what = false;
if (!what) cout << "The same!" << endl;
else cout << "Not the same" << endl;
}
int getNumb(int x)
{
cout << "Enter a prime number below 8" << endl;
cin >> x;
return x;
}
int main()
{
int b(0);
getNumb(b);
bool prime(false);
if (2 == b) prime = true;
elseif (3 == b) prime = true;
elseif (5 == b) prime = true;
elseif (7 == b) prime = true;
if (prime) cout << "Yeah baby!" << endl;
else cout << "Nope, not a prime!" << endl;
}