Testing the Boolean data type - true/false, 0/1 or yes/no in C++


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Testing the Boolean data type: true/false, 0/1 or yes/no in C++ programming

To show: How to use the Boolean data type in C++ programming for true/false condition




// playing with bool type, true/false.

#include <iostream>

using namespace std;


// user defined function

bool func()


// function returns a bool type

return NULL;

// NULL is converted to Boolean false, same as statement 'return false;'



int main(void)


// Boolean variable

bool val = false;

// i is neither Boolean-true nor Boolean-false

int i = 1;

int g = 5;

// j is neither Boolean-true nor Boolean-false

float j = 3.02;


cout<<"Given the test value: "<<endl;

cout<<"\nbool val = false "<<endl;

cout<<"int i = 1 "<<endl;

cout<<"int g = 5 "<<endl;

cout<<"float j = 3.02 "<<endl;



// tests on integers

if(i == true)

cout<<"True: value i is 1"<<endl;


if(i == false)

cout<<"False: value i is 0"<<endl;



cout << "g is true."<<endl;


cout << "g is false."<<endl;


// to test j's truth value, cast it to bool type.

if(bool(j) == true)

cout<<"Boolean j is true."<<endl;


// test Boolean function returns value

val = func();

if(val == false)

cout<<"func() returned false."<<endl;


if(val == true)

cout<<"func() returned true."<<endl;

// false is converted to 0

return false;



Output example:


Given the test value:

bool val = false

int i = 1

int g = 5

float j = 3.02


True: value i is 1

g is true.

Boolean j is true.

func() returned false.

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index