4.9 — Boolean values – Learn C++ (2024)

In real-life, it’s common to ask or be asked questions that can be answered with “yes” or “no”. “Is an apple a fruit?” Yes. “Do you like asparagus?” No.

Now consider a similar statement that can be answered with a “true” or “false”: “Apples are a fruit”. It’s clearly true. Or how about, “I like asparagus”. Absolutely false (yuck!).

These kinds of sentences that have only two possible outcomes: yes/true, or no/false are so common, that many programming languages include a special type for dealing with them. That type is called a Boolean type (note: Boolean is properly capitalized in the English language because it’s named after its inventor, George Boole).

Boolean variables

Boolean variables are variables that can have only two possible values: true, and false.

To declare a Boolean variable, we use the keyword bool.

bool b;

To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.

bool b1 { true };bool b2 { false };b1 = false;bool b3 {}; // default initialize to false

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:

bool b1 { !true }; // b1 will be initialized with the value falsebool b2 { !false }; // b2 will be initialized with the value true

Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integral values: true is stored as integer 1, and false is stored as integer 0. Similarly, when Boolean values are evaluated, they don’t actually evaluate to “true” or “false”. They evaluate to the integers 0 (false) or 1 (true). Because Booleans store integral values, they are considered to be an integral type.

Printing Boolean values

When we print Boolean values, std::cout prints 0 for false, and 1 for true:

#include <iostream>int main(){ std::cout << true << '\n'; // true evaluates to 1 std::cout << !true << '\n'; // !true evaluates to 0 bool b {false}; std::cout << b << '\n'; // b is false, which evaluates to 0 std::cout << !b << '\n'; // !b is true, which evaluates to 1 return 0;}

Outputs:

1001

If you want std::cout to print true or false instead of 0 or 1, you can use std::boolalpha. Here’s an example:

#include <iostream>int main(){ std::cout << true << '\n'; std::cout << false << '\n'; std::cout << std::boolalpha; // print bools as true or false std::cout << true << '\n'; std::cout << false << '\n'; return 0;}

This prints:

10truefalse

You can use std::noboolalpha to turn it back off.

Integer to Boolean conversion

When using uniform initialization, you can initialize a variable using integer literals 0 (for false) and 1 (for true) (but you really should be using false and true instead). Other integer literals cause compilation errors:

#include <iostream>int main(){bool bFalse { 0 }; // okay: initialized to falsebool bTrue { 1 }; // okay: initialized to truebool bNo { 2 }; // error: narrowing conversions disallowedstd::cout << bFalse << bTrue << bNo << '\n';return 0;}

However, in any context where an integer can be converted to a Boolean, the integer 0 is converted to false, and any other integer is converted to true.

#include <iostream>int main(){std::cout << std::boolalpha; // print bools as true or falsebool b1 = 4 ; // copy initialization allows implicit conversion from int to boolstd::cout << b1 << '\n';bool b2 = 0 ; // copy initialization allows implicit conversion from int to boolstd::cout << b2 << '\n';return 0;}

This prints:

truefalse

Note: bool b1 = 4; may generate a warning. If so you’ll have to disable treating warnings as errors to compile the example.

Inputting Boolean values

Inputting Boolean values using std::cin sometimes trips new programmers up.

Consider the following program:

#include <iostream>int main(){bool b{}; // default initialize to falsestd::cout << "Enter a boolean value: ";std::cin >> b;std::cout << "You entered: " << b << '\n';return 0;}
Enter a Boolean value: trueYou entered: 0

Wait, what?

It turns out that std::cin only accepts two inputs for Boolean variables: 0 and 1 (not true or false). Any other inputs will cause std::cin to silently fail. In this case, because we entered true, std::cin silently failed. A failed input will also zero-out the variable, so b is assigned the value false. Consequently, when std::cout prints a value for b, it prints 0.

To allow std::cin to accept false and true as inputs, the std::boolalpha option has to be enabled:

#include <iostream>int main(){bool b{};std::cout << "Enter a boolean value: ";// Allow the user to enter 'true' or 'false' for boolean values// This is case-sensitive, so True or TRUE will not workstd::cin >> std::boolalpha;std::cin >> b;std::cout << "You entered: " << b << '\n';return 0;}

However, when std::boolalpha is enabled, 0 and 1 will no longer be interpreted as Booleans inputs (they both resolve to false as does any non-true input).

Warning

Enabling std::boolalpha will only allow lower-cased false or true to be accepted. Variations with capital letters will not be accepted.

Boolean return values

Boolean values are often used as the return values for functions that check whether something is true or not. Such functions are typically named starting with the word is (e.g. isEqual) or has (e.g. hasCommonDivisor).

Consider the following example, which is quite similar to the above:

#include <iostream>// returns true if x and y are equal, false otherwisebool isEqual(int x, int y){ return x == y; // operator== returns true if x equals y, and false otherwise}int main(){ std::cout << "Enter an integer: "; int x{}; std::cin >> x; std::cout << "Enter another integer: "; int y{}; std::cin >> y; std::cout << std::boolalpha; // print bools as true or false std::cout << x << " and " << y << " are equal? "; std::cout << isEqual(x, y) << '\n'; // will return true or false return 0;}

Here’s output from two runs of this program:

Enter an integer: 5Enter another integer: 55 and 5 are equal? true
Enter an integer: 6Enter another integer: 46 and 4 are equal? false

How does this work? First we read in integer values for x and y. Next, the expression isEqual(x, y) is evaluated. In the first run, this results in a function call to isEqual(5, 5). Inside that function, 5 == 5 is evaluated, producing the value true. The value true is returned back to the caller to be printed by std::cout. In the second run, the call to isEqual(6, 4) returns the value false.

Boolean values take a little bit of getting used to, but once you get your mind wrapped around them, they’re quite refreshing in their simplicity! Boolean values are also a huge part of the language -- you’ll end up using them more than all the other fundamental types put together!

We’ll continue our exploration of Boolean values in the next lesson.

Next lesson4.10Introduction to if statementsBack to table of contentsPrevious lesson4.8Floating point numbers
4.9 — Boolean values – Learn C++ (2024)

References

Top Articles
5 Best Bangladesh VPNs | Bangladesh Servers - Fast - Secure
5 Best Smart Switch With No Neutral Wire
Die Reiseauskunft auf bahn.de - mit aktuellen Alternativen gut ans Ziel
Luxiconic Nails
Look Who Got Busted New Braunfels
How Much Is Vivica Fox Worth
Superhot Unblocked Games
Indiana girl set for final surgery 5 years after suffering burns in kitchen accident
Anonib Altoona Pa
Guardians Of The Galaxy Vol 3 Full Movie 123Movies
Nashville Tranny
Cratebrowser
Gt7 Roadster Shop Rampage Engine Swap
Join MileSplit to get access to the latest news, films, and events!
Stone Eater Bike Park
Sermon Collections, Sermons, Videos, PowerPoint Templates, Backgrounds
Elisabeth Fuchs, Conductor : Magazine : salzburg.info
Rick Harrison Daughter Ciana
Fly Fit Bungee Rome Ga
55000 Pennies To Dollars
A Man Called Otto Showtimes Near Palm Desert
2Lookmovie
Magicseaweed Capitola
Kentuky Fried Chicken Near Me
Hca Florida Middleburg Emergency Reviews
Craigsliststcloud
Meritas Health Patient Portal
Acbl Homeport
Brublackvip
Quattrocento, Italienische Kunst des 15. Jahrhunderts
The Flash 2023 1080P Cam X264-Will1869
Marshfieldnewsherald Obituary
Hose Woe Crossword Clue
Basis Independent Brooklyn
Brian Lizer Life Below Zero Next Generation
Horoscope Today: Astrological prediction September 9, 2024 for all zodiac signs
Stellaris How To Get Subjugation Casus Belli
From Iceland — Northern Comfort: A Turbulent Ride Of Comedy
Seatgeek Seat View
Edenmodelsva
My Scheduler Hca Cloud
Registrar Utd
Strange World Showtimes Near Amc Marquis 16
Austin Powers Judo Chop Gif
Realidades 2 Capitulo 2B Answers
'It's huge': Will Louisville's Logan Street be the next Findlay or Pike Place market?
Southwest Flight 238
11 Fascinating Axolotl Facts
Barber Gym Quantico Hours
Gunsmoke Noonday Devil Cast
Akc Eo Tryouts 2022
Bòlèt New York Soir
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 5614

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.