Open In App

GFact | Why Printing Boolean in C++ Display as 0 and 1

Last Updated : 03 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Have you ever tried to print some boolean value in the cout section of your code? If yes, then you must have got the output as 0 or 1. But what hapenned to the Boolean value? Why didn’t it got printed in the first place? How to get print the boolean value as it is in the output section? 

What happens when printing Boolean value in C++?

Consider the following code where we are simply trying to print the Boolean value “false”.

C++




#include <iostream>
 
int main()
{
  std::cout << false << std::endl;
}


Expected Output:

false

Actual Output:

0

Why did 0 or 1 got printed instead of Boolean value in C++?

The reason for this lies in the C++ standard documentation

Boolean type

bool — type, capable of holding one of the two values: true or false.

These values – true and false, are stored in the memory as 0 and 1 respectively. As a result, everytime true or false is used, it is converted to 0 and 1 respectively and hence the same is printed in output.

How to Print True or False Boolean Values in C++?

1. Using if else

C++




#include <iostream>
using namespace std;
 
int main()
{
 
    bool value = false;
    if (value == false)
        cout << "false";
    else
        cout << "true";
    return 0;
}


Output

false

2. Using boolalpha conversion

The standard streams have a boolalpha flag that determines what gets displayed — when it’s false, they’ll display as 0 and 1. When it’s true, they’ll display as false and true.

There’s also an std::boolalpha manipulator to set the flag, 

C++




#include <iostream>
using namespace std;
 
int main()
{
    cout << std::boolalpha << "false";
    return 0;
}


Output

false


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads