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 output std::boolalpha. This doesn’t output anything, but manipulates the way std::cout outputs bool values.

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, you must first input to std::boolalpha:

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

However, when std::boolalpha is enabled for input, 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 for input will only allow lower-cased false or true to be accepted. Variations with capital letters will not be accepted. 0 and 1 will also no longer be accepted.

Note that we use std::cin >> std::boolalpha; to input bool values as true or false, and std::cout << std::boolalpha; to output bool values as true or false. These are independent controls that can be turned on (using std::boolalpha) or off (using std::noboolalpha) separately.

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)

FAQs

What is the boolean value for C++? ›

For this, C++ has a bool data type, which can take the values true (1) or false (0).

How to check if a boolean is true in C++? ›

Boolean Variables and Data Type

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

What is the 3 value bool in C++? ›

The tribool class acts like the built-in bool type, but for 3-state boolean logic. The three states are true , false , and indeterminate , where the first two states are equivalent to those of the C++ bool type and the last state represents an unknown boolean value (that may be true or false , we don't know).

What is the default boolean value in C++? ›

The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as false). All the values stored in the array in the above program are garbage values and are not fixed.

What is an example of a boolean operator in C++? ›

Logical Operators
OperatorNameExample
&&Logical andx < 5 && x < 10
||Logical orx < 5 || x < 4
!Logical not!(x < 5 && x < 10)

What is the difference between Boolean and bool in C++? ›

Semantically, nothing. They both MEAN the same thing, a data type of true or false.

What does == 0 mean in C++? ›

if (number == 0) { … }: This is a conditional statement that checks if the value of the number is equal to 0. If it is, the code inside the if block executes, indicating that the number is zero.

Is Boolean yes or true? ›

A Boolean is a type of data that has only two possible values: true or false. You can think of a boolean like the answer to a yes or no question. If the answer is yes, the Boolean value is true. If the answer is no, the boolean value is false.

Is false 0 or 1? ›

Instead, comparison operators generate 0 or 1; 0 represents false and 1 represents true.

How to declare boolean in C? ›

It is necessary to import the header file, stdbool. h to declare boolean variables to use boolean value in C. bool variable_name; The “ bool ” keyword is used to declare boolean variables.

What is the return value of a bool in C++? ›

Unfortunately, when C++ outputs bools, it does not display the words true and false, but rather the integers 1 and 0.

How to write a boolean in C++? ›

In C++ the boolean type is called bool. Boolean variables work just like the other types: bool fred; fred = true; bool testResult = false; The first line is a simple variable declaration; the second line is an assignment, and the third line is a combination of a declaration and as assignment, called an initialization.

Is true always 1 in C++? ›

C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0. The coding standards for this course require you to do that.

What is the bool flag in C++? ›

bool stands for boolean, boolean is a value that can be only 1 of 2 states true or false, or on or off, or 1 or 0 these all represent the same thing, a flag is a variable that is used in a conditional.

C++ Booleans - W3SchoolsW3Schoolshttps://www.w3schools.com ›

C++ Booleans. Very often, in programming, you will need a data type that can only have one of two values, like: YES / NO; ON / OFF; TRUE / FALSE. For this, C++ ...
A boolean data type in C++ is defined using the keyword bool . Usually, 1 1 1 ( true ) and 2 2 2 ( false ) are assigned to boolean variables as their default nu...
In the old days of C, there was no boolean type. People used the int for storing boolean data, and it worked mostly. Zero was false and everything else was true...

What is the Boolean 0 and 1 in C++? ›

A C++ booleans data type is used to hold only two values; it can be either True or False. In C++, 1 refers to True, and 0 refers to False. Let's see the syntax for defining a C++ booleans variable. You can also do a free certification of Basics of C++.

What is Boolean value in C? ›

Boolean in C

The bool data type is one of the fundamental data types in C. It is used to hold only two values i.e. true or false . The C program returns boolean values as integers, 0 and 1 . The boolean meaning of these integers are: 0 indicates a false value.

How many bits is a Boolean C++? ›

8 bools in 1 byte, the 1 bit boolean.

What is the return of a Boolean value in C++? ›

Returning Boolean values from Boolean expressions

A Boolean expression in C++ is that type of expression that will return a Boolean value: either 1 ( true ) or 0 ( false ). When we write a Boolean expression to compare two values in C++ using the comparison operator, the return value is a Boolean.

References

Top Articles
What is the culvers flavor of the day? - Chef's Resource
The Best Fast Food Desserts, According to the MUNCHIES Staff
Musas Tijuana
Current Time In Maryland
Jay Cutler of NFL Biography, Wife, Career Stats, Net Worth &amp; Salary
Cost Of Fax At Ups Store
Best Seafood Buffet In Laughlin Nevada
Creglist Tulsa
Mensenlinq: Overlijdensberichten zoeken in 2024
Tinyzonehd
Msu Ro
Craislist Vt
Farmers And Merchants Bank Broadway Va
Momokun Leaked Controversy - Champion Magazine - Online Magazine
Adt First Responder Discount
Eggy Car Unblocked - Chrome Web Store
Her Triplet Alphas Chapter 32
Hannaford Weekly Flyer Manchester Nh
Nypsl-E Tax Code Category
Mobiloil Woodville Tx
ZQuiet Review | My Wife and I Both Tried ZQuiet for Snoring
NFL Week 1 coverage map: Full TV schedule for CBS, Fox regional broadcasts | Sporting News
Craigslist Org Hattiesburg Ms
Contenidos del nivel A2
New Jersey Map | Map of New Jersey | NJ Map
Kroger Liquor Hours
Storm Prediction Center Convective Outlook
Experience the Convenience of Po Box 790010 St Louis Mo
Henry Metzger Lpsg
Alamy Contributor Forum
Beetrose 'Planten un Blomen' - Rosa 'Planten un Blomen' ADR-Rose
Live2.Dentrixascend.com
Pioneer Justice Court Case Lookup
Connection | Scoop.it
Aldi Sign In Careers
Harvestella Farming Guide | Locations & Crop Prices | TechRaptor
Peloton Guide Stuck Installing Update
Publix Super Market At Lockwood Commons
Framingham Risk Score Calculator for Coronary Heart Disease
Manage your photos with Gallery
The dangers of statism | Deirdre McCloskey
Colorado Pick 3 Lottery
600 Aviator Court Vandalia Oh 45377
Walgreens Pharmacy On Jennings Station Road
Blog:Vyond-styled rants -- List of nicknames (blog edition) (TouhouWonder version)
Tapana Movie Online Watch 2022
Used Cars For Sale in Pretoria | Quality Pre-Owned Cars | Citton Cars
Dungeon Family Strain Leafly
The many times it was so much worse
Democrat And Chronicle Obituaries For This Week
C Weather London
Carenow Urgent Care - Eastchase Fort Worth Photos
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 5575

Rating: 4.8 / 5 (48 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.