Monday, January 17, 2011

Boolean Values

The next data type we’re going to look at is the boolean data type. Boolean variables only have two possible values: true (1) and false (0).
To declare a boolean variable, we use the keyword bool.
1bool bValue;
When assigning values to boolean variables, we use the keywords true and false.
1bool bValue1 = true; // explicit assignment
2bool bValue2(false); // implicit assignment
Just as the unary minus operator (-) can be used to make an integer negative, the logical NOT operator (!) can be used to flip a boolean value from true to false, or false to true:
1bool bValue1 = !true; // bValue1 will have the value false
2bool bValue2(!false); // bValue2 will have the value true
When boolean values are evaluated, they actually don’t evaluate to true or false. They evaluate to the numbers 0 (false) or 1 (true). Consequently, when we print their values with cout, it prints 0 for false, and 1 for true:
1bool bValue = true;
2cout << bValue << endl;
3cout << !bValue << endl;
4
5bool bValue2 = false;
6cout << bValue2 << endl;
7cout << !bValue2 << endl;
Outputs:
1
0
0
1
One of the most common uses for boolean variables is inside if statements:
1bool bValue = true;
2if (bValue)
3    cout << "bValue was true" << endl;
4else
5    cout << "bValue was false" << endl;
Output:
bValue was true
Don’t forget that you can use the logical not operator to reverse a boolean value:
1bool bValue = true;
2if (!bValue)
3    cout << "The if statement was true" << endl;
4else
5    cout << "The if statement was false" << endl;
Output:
The if statement was false
Boolean values are also useful as the return values for functions that check whether something is true or not. Such functions are typically named starting with the word Is:
01#include <iostream>
02
03using namespace std;
04
05// returns true if x and y are equal
06bool IsEqual(int x, int y)
07{
08    return (x == y); // use equality operator to test if equal
09}
10
11int main()
12{
13    cout << "Enter a value: ";
14    int x;
15    cin >> x;
16
17    cout << "Enter another value: ";
18    int y;
19    cin >> y;
20
21    bool bEqual = IsEqual(x, y);
22    if (bEqual)
23        cout << x << " and " << y << " are equal"<<endl;
24    else
25        cout << x << " and " << y << " are not equal"<<endl;
26    return 0;
27}
In this case, because we only use bEqual in one place, there’s really no need to assign it to a variable. We could do this instead:
1if (IsEqual(x, y))
2    cout << x << " and " << y << " are equal"<<endl;
3else
4    cout << x << " and " << y << " are not equal"<<endl;
IsEqual() evaluates to true or false, and the if statement then branches based on this value.
Boolean variables are quite refreshing in their simplicity!
One additional note: when converting integers to booleans, the integer zero resolves to boolean false, whereas non-zero integers all resolve to true.

No comments: