×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

bool data type in C++

C++ | bool data type with examples: In this tutorial, we are going to learn about the Boolean (bool) data type, its usages, syntaxes and examples.
Submitted by IncludeHelp, on June 06, 2020

bool data type in C++

In C++ programming language, to deal with the Boolean values – C++ added the feature of the bool data type. A bool variable stores either true (1) or false (0) values.

Note that, In C++, true and false are the inbuilt keywords and they represent 1 and 0 respectively.

So, whenever we need to work with such variables in which we have to store only two values i.e. the variable to hold status like, ON/OFF, YES/NO, TRUE/FALSE, etc we can use bool type variable.

Syntax

bool variable_name;

Example 1

#include <iostream>
using namespace std;

int main()
{
    bool var1 = true;
    bool var2 = false;
    bool var3 = 1;
    bool var4 = 0;

    //printing the values
    cout << "var1 : " << var1 << endl;
    cout << "var2 : " << var2 << endl;
    cout << "var3 : " << var3 << endl;
    cout << "var4 : " << var4 << endl;

    return 0;
}

Output

var1 : 1
var2 : 0
var3 : 1
var4 : 0

Example 2

#include <iostream>
using namespace std;

int main()
{
    bool status = true;

    if (status)
        cout << "It's true..." << endl;
    else
        cout << "It's false..." << endl;

    status = false;

    if (status)
        cout << "It's true..." << endl;
    else
        cout << "It's false..." << endl;

    return 0;
}

Output

It's true...
It's false...

Note: Any non-zero value considers as true and zero considers as false.

Example 3

#include <iostream>
using namespace std;

int main()
{
    bool x = true;

    cout << "x : " << x << endl;

    x = -1;
    cout << "x : " << x << endl;

    x = -123.45f;
    cout << "x : " << x << endl;

    x = "Hello";
    cout << "x : " << x << endl;

    x = 123.456f;
    cout << "x : " << x << endl;

    x = 0;
    cout << "x : " << x << endl;

    x = NULL;
    cout << "x : " << x << endl;

    return 0;
}

Output

x : 1
x : 1
x : 1
x : 1
x : 1
x : 0
x : 0

Also read: Use of bool in C language

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.