C++ Booleans

C++ Booleans

Very often in programming, you will need a data type that can only have one of two values, like:

For this, C++ has a bool data type.

Boolean Values

A boolean variable is declared with the bool keyword and can only take the values true or false.

Example

bool isCodingFun = true;
bool isFishTasty = false;

cout << isCodingFun; // Outputs 1 (true) cout << isFishTasty; // Outputs 0 (false)

Note: In C++, true is represented as 1 and false as 0 when outputted.

Boolean Expressions

A boolean expression returns a boolean value (1 or 0). You can use comparison operators to create boolean expressions:

Example

int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9

Booleans are fundamental to conditional statements like if...else, which you will learn about next!


Exercise

?

What value does C++ output when printing a boolean variable set to true?