 Store Logical Values in C++ - dummies

The result of a logical operation in C++ can be assigned to a variable of type bool. The term bool refers to Boolean algebra, which is the algebra of logic. This was invented by a British mathematician, George Boole, in the 19th century.

```int n1 = 1;
int n2 = 2;
bool b;
b = (n1 == n2);```

This expression highlights the difference between the assignment operator = and the comparison operator ==. The expression says, “Compare the variables n1 and n2. Store the results of this comparison in the variable b.

The following BoolTest program demonstrates the use of a bool variable:

```// BoolTest - compare variables input from the
//            keyboard and store the results off
//            into a logical variable
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// set output format for bool variables
// to true and false instead
// of 1 and 0
cout.setf(cout.boolalpha);
// input two values
int nArg1;
cout << "Input value 1: ";
cin >> nArg1;
int nArg2;
cout << "Input value 2: ";
cin >> nArg2;
// compare the two variables and store the results
bool b;
b = nArg1 == nArg2;
cout << "The statement, " << nArg1
<< " equals "        << nArg2
<< " is "            << b
<< endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
cout << "Press Enter to continue..." << endl;
cin.ignore(10, 'n');
cin.get();
return 0;
}```

The first line cout.setf() makes sure that the bool variable b is output as “true” or “false”.

The program inputs two values from the keyboard and displays the result of the equality comparison:

```Input value 1: 5
Input value 2: 5
The statement, 5 equals 5 is true
Press Enter to continue...```

The special value endl inserts a newline. The difference between the value endl and the character ‘n’ is subtle.