Navigation



2.6 — Boolean Values

The next data type we’re going to look at is the boolean data type. Boolean variables only have two possible values: true (1) and false (0).

To declare a boolean variable, we use the keyword bool.

bool bValue;

When assigning values to boolean variables, we use the keywords true and false.

bool bValue1 = true; // explicit assignment
bool bValue2(false); // implicit assignment

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 bValue1 = !true; // bValue1 will have the value false
bool bValue2(!false); // bValue2 will have the value true

When boolean values are evaluated, they actually don’t evaluate to true or false. They evaluate to the numbers 0 (false) or 1 (true). Consequently, when we print their values with cout, it prints 0 for false, and 1 for true:

bool bValue = true;
cout << bValue << endl;
cout << !bValue << endl;

bool bValue2 = false;
cout << bValue2 << endl;
cout << !bValue2 << endl;

Outputs:

1
0
0
1

One of the most common uses for boolean variables is inside if statements:

bool bValue = true;
if (bValue)
    cout << "bValue was true" << endl;
else
    cout << "bValue was false" << endl;

Output:

bValue was true

Don’t forget that you can use the logical not operator to reverse a boolean value:

bool bValue = true;
if (!bValue)
    cout << "The if statement was true" << endl;
else
    cout << "The if statement was false" << endl;

Output:

The if statement was false

Boolean values are also useful as the return values for functions that check whether something is true or not. Such functions are typically named starting with the word Is:

#include <iostream>

using namespace std;

// returns true if x and y are equal
bool IsEqual(int x, int y)
{
    return (x == y); // use equality operator to test if equal
}

int main()
{
    cout << "Enter a value: ";
    int x;
    cin >> x;

    cout << "Enter another value: ";
    int y;
    cin >> y;

    bool bEqual = IsEqual(x, y);
    if (bEqual)
        cout << x << " and " << y << " are equal"<<endl;
    else
        cout << x << " and " << y << " are not equal"<<endl;
    return 0;
}

In this case, because we only use bEqual in one place, there’s really no need to assign it to a variable. We could do this instead:

    if (IsEqual(x, y))
        cout << x << " and " << y << " are equal"<<endl;
    else
        cout << x << " and " << y << " are not equal"<<endl;

IsEqual() evaluates to true or false, and the if statement then branches based on this value.

Boolean variables are quite refreshing in their simplicity!

One additional note: when converting integers to booleans, the integer zero resolves to boolean false, whereas non-zero integers all resolve to true.

2.7 — Chars
Index
2.5 — Floating point numbers

48 comments to 2.6 — Boolean Values

  • Renu

    Correct me if I am wrong .Shouldnt function name be “isEqual” instead of “IsEqual”? or that convention mostly applies to variable names.

    • My personal preference is that variable names start with lower case and function (and class) names start with upper case. This makes them easier to distinguish.

    • Ken

      Correct me if I am wrong…

      If the Value of TRUE is 1 (00000001), Doesn’t (!TRUE) make the value to be equal to (111111110) internally? If that is the case then evaluating:
      if (!TRUE) will always be TRUE.

      • Ashish Gupta

        Hi,

        Actually what u r doing is not correct. u r performing bit wise not that is ~ operator in c.
        now u r using operator ! which actually ORs all the bits of the value and then compliments it i.e.
        if TRUE is 1(00000001) then ORing will give its value 1(binary not 00000001) this is only a bit so now it will compliment it to 0 and then return the resulting false(000000000).

        For futher query you can ask me..
        Thnks,

  • some guy

    I’m confused as to why you make the IsEqual function a bool, wouldn’t making it an int function work just as well? Or is it declared as a bool function so you have an idea of what the return values will be and what the function does? Sorry if I sound like a newbie :p

    • IsEqual function isn’t a bool, it returns a bool. Boolean values are used to represent values that can only be true or false. When we’re talking about whether a value is equal, either it is (true), or it isn’t (false). Consequently, it makes more sense to return a bool than an int. While technically returning an int would work (returning the value 1 if the parameters are equal, and 0 otherwise), returning a bool is more intuitive and leaves less room for errors to be made.

  • programmer

    I have problem actually I don’t know how to use the boolean with ( cin ) ..

    like this example:

    if i want to ask some one about his car ?

    ===========
    bool car;

    < <
    ====================
    cout << " IS your car new or not ? " ;
    cin >> car;
    ===================
    

    =====
    is the above good solution or not ??

    i’m witing for your answer

    thank you so much

    • When trying to cin boolean values, if the user enters the number 0, this will be treated as the value false. If the user enters anything else, it will be treated as the value true.

      There are several ways to proceed:
      * Tell the user to enter 0 for no and 1 for yes and then cin a bool.
      * Tell the user to enter ‘y’ or ‘n’ and then cin a character.

      Once you get to the lesson on strings, you could also do this:
      * Tell the user to enter “yes” or “no” and then cin a string.

  • [...] 2007 Prev/Next Posts « 2.6 — Boolean Values | Home | 2.8 — Constants » Saturday, June 9th, 2007 at 7:07 [...]

  • another_programmer

    Yup, I had trouble with this one quite a while ago, one thing you’d have to remember is that bool is based on being simply on or off, where if something exists, it’s on, and if it doesn’t it’s off. 1 or 0.

    Boolean values are more ideally used if preexisting values exist much like radio buttons, in HTML for example…

    <form>
    Is your car new or not?<br>
    <input name="newCar" type="radio" value="1" /> Yes<br>
    <input name="newCar" type="radio" value="0" /> No<br>
    </form>

  • Pieter

    You forgot
    using namespace std;
    Hey look what I learned thanks to you =)

    [ Indeed I did. Thanks for pointing it out. -Alex ]

  • Kiran

    Please correct me if I am wrong:
    If the Value of TRUE is 1 (00000001), Doesn’t (!TRUE) make the value to be equal to (111111110) internally? If that is the case then evaluating:
    if (!TRUE) will always be TRUE.

    • Ashish Gupta

      Hi,

      Actually what u r doing is not correct. u r performing bit wise not that is ~ operator in c.
      now u r using operator ! which actually ORs all the bits of the value and then compliments it i.e.
      if TRUE is 1(00000001) then ORing will give its value 1(binary not 00000001) this is only a bit so now it will compliment it to 0 and then return the resulting false(000000000).

      For futher query you can ask me..on new_programers@yahoo.com
      Thnks,

    • kiran darling lund logi mera…mai tumhri chut mai jeeb dalunga kiran tumko bahut maza ayega…tumhri chut mai jab apna lund dalunga to tum madhosh ho jyo go

  • Spock

    Hey Alex,

    Nice tutorial section! Some comments that might improve readability of this section:

    1. Mention that the test x==y will output a 0 if false and a 1 if true and discuss the use of this equality as a logic ‘test’. It took me a few moments to appreciate that for myself.

    2. Logic commands have not been discussed in the tutorial yet (if, not etc) so someone new to programming might find this confusing.

    You could also mention that if(1) runs the first command in an if statement and if(0) runs the ‘else’ statement. Interestingly if(5), if(11) and all if(!=0) has the same effect as if(1). i.e all non-zero values are true in the context of the if statement.

    :)

    • Thanks for your thoughts. I added a comment about conversion of integers to booleans because that’s not very intuitive to new programmers. Your other comments are valid, but are discussed in future chapters when I tackle those specific topics.

  • Noha

    Hey!
    In which cases do we use the implicit assignment?

     bool bValue2(false); 
  • sra1

    Hi Alex!
    I dont know why this code is not working in my computer.

    #include "stdafx.h"
    #include <iostream>
    
    using namespace std;
    bool IsEqual(int x,int y)
    {
    
    	return(x == y);
    }
    
    int main()
    {
    
    	cout << "enter value of x: " << endl;
    	int x;
    	cin >> x;
    
        cout << "enter value of y: " << endl;
    	int y;
    	cin >> y;
    
    	bool bEqual = IsEqual(x,y);
    
    	if(bEqual)
    		cout << x << "and" << y << "are equal" <<endl;
    	else
    		cout << x << "and" << y << "are not equal" <<endl;
    
    return 0;
    }
    

    Please help.

  • sra1

    the error is
    1>—— Build started: Project: HelloWorld, Configuration: Debug Win32 ——
    1>Compiling…
    1>isequal.cpp
    1>Linking…
    1>isequal.obj : error LNK2005: _main already defined in Function.obj
    1>C:\Documents and Settings\sravan\My Documents\Visual Studio 2008\Projects\HelloWorld\Debug\HelloWorld.exe : fatal error LNK1169: one or more multiply defined symbols found
    1>Build log was saved at “file://c:\Documents and Settings\sravan\My Documents\Visual Studio 2008\Projects\HelloWorld\HelloWorld\Debug\BuildLog.htm”
    1>HelloWorld – 2 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

  • someone

    Please i need some help…
    Can please anyone review this code? It is supossed to accept the input of 2 numbers, the asks for the answer if they are equal and not equal and says if the answer is either right or not:

    #include <iostream>
    
    using namespace std;
    
    bool IsEqual( int x, int y ) ;
    
    int main()
    {
        int x ;
        int y ;
        bool bSecond;
        cout<< " First input: " << endl;
        cin >> x ;
        cout<< " Second input: " << endl;
        cin >> x ;
        bool bFirst = IsFalse( x, y );
        cout<< "They are equal or not equal ?\n -> 1 - Equal ; 0 - Not equal ; " << endl;
        cin >> bSecond ;
        if( bFirst == bSecond )
            {
                   cout<<" The answer is right! " << endl;
                   cin.get();
            }
        else
            {
                   cout<<" The answer is wrong " << endl;
                   cin.get();
            }
        cin.get();
    }
    
    bool IsEqual( int x, int y)
    {
         return( x==y );
    }
    

    Thanks!

  • joel

    Great Tutorials, well written and structured. many thanks.

    coming from a background in Oracle and using mainly PL/SQL i have gotten used to the idea that booleans are tristate (true, false or null/unknown) and so an if statement against an uninitialsed boolean var would always return null (and thereby only be handled by “else”) without any warnings – dangerous.

    It might be worth noting for people like me that uninitialised boolean variables, aside from raising a warning at compile and a “break” at runtime (in VC2008 at least), will almost always return true (i assume this because the uninitialised memory address will almost always contain a non-zero value as below).

    int main()
    {
    	bool bEqual;
    
    	if (bEqual)
    		cout << "is true with value " << bEqual << endl;
    	else
    		cout << "is not true with value " << bEqual << endl;
    
        return 0;
    }
    
  • Sam

    I don’t get how it can run the function bool IsEqual(int x, int y), if there is no function call in the program later. I would figure you would need,

    bool Isequal(x,y); <—-in main function to call the IsEqual function?

    for the program to read

    bool IsEqual(int x, int y)
    07.{
    08. return (x == y); // use equality operator to test if equal
    09.}

    so how does it work without a function call being made?

    • Collin

      the if statement calls the function to check if (x==y)

      if (IsEqual(x, y))
      cout << x << " and " << y << " are equal"<<endl;
      else
      cout << x << " and " << y << " are not equal"<<endl;
      
  • Alex

    Could someone please give me a definitive answer about the difference between explicit and implicit assignments.

    
    int i = 1;
    int j(1);
    

    Thanks

    • Daniel

      I’ve never seen that type of assignment used for a built-in, although I do not doubt that it works. I believe that “int i = 1;” uses int’s default constructor THEN uses int’s assignment operator. Whereas “int j(1);” uses a version of int’s constructor which accepts an integer. In theory the second should be more efficient although compilers are most likely smart enough to optimise away the extra step.

  • Stephan

    Hi Alex (Admin)!

    Great site.
    Just wanted to say that I find your site extremely educational, and for me, easy to follow. Good work!

    P.S.
    I get just as much fun/learning reading the comments at the end of the tutorial as I do from the lessons. I can’t finish a section without reading the comments!

    Brilliant!!!

  • Mac

    Hi, i tried to make this program work with three numbers:

    i.e.
    return (x == y == z)

    the program compiled fine and ran, but did only gave the result for “else” (false)

    after i took away “int z” it worked just fine…

    does bool only work for two variables?

    • The reason is when you say a == b == c, first it checks a and b and if those two numbers are equal, you are trying to check if c is equal to 1(true). Try this:

      bool IsEqual(int a, int b, int c)
      {
      if(a == b)
      {
      if(b == c)
      return true;
      }
      else
      return false;
      }

  • Guntis

    Yay, I think I completely understand how bool works now.
    Thanks Alex, this is so much better than even some of those books on cpp.

    P.S. Here’s my little test that succeeded btw.

    bool isEqual(int x, int y)
    {
    	return (x == y);
    }
    int main()
    {
    	cout << "Enter a value:\t\t ";
    	int x;
    	cin >> x;
    
    	cout << "Enter another value:\t ";
    	int y;
    	cin >> y;
    
    	if (isEqual(x, y))
    		cout << "Numbers were equal!" << endl;
    	else
    		cout << "Numbers were not equal" << endl;
    
    	bool bZero(1);
    
    	if (x == 0)
    		bZero = 1;
    	else
    		if (y == 0)
    			bZero = 1;
    		else
    			bZero = 0;
    
    	if (bZero == 1)
    		cout << "One of numbers was 0" << endl;
    	else
    		return 0;
    
    }
    
  • joha

    wouldnt it be the same to put instead of x==y, this: x=y????
    i tried and got the same result so…..what is the difference and when do I use each operator????

    Thanks..

  • gurbux

    hey nice explanation alex very helpfull………..

  • xero

    I want to ask why following code works?

    #include
    int main()
    {
    using namespace std;
    int x;
    cout << "Please feed in the first number" <> x;
    int y;
    cout << "Please feed in the second number" <> y;
    bool z;
    if (x==y)
    z = true;
    else
    z = false;
    if (z)
    cout << "Both digits are equal" << endl;
    else
    cout << "Both digits are different" << endl;
    return 0;
    }

    When the user feeds in two different numbers then the statement which says
    if (z)
    must hold 0 as z and in return should type "Both digits are equal" because this cout statement follows if (z) statement.
    Please comment…

  • Can anyone help me in this plz i cant figure out my mistake

    #include
    #include
    #include

    using namespace std;

    int main()
    {
    ifstream in;
    char ch;

    in.open(“Saad.txt”);

    in>>ch;
    while(in.getline(in,11));
    {
    cout<<ch;
    }

    in.close();
    getch();
    return 0;
    }

    file:-

    p12-6094 Saad Asghar Keen

    p12-6049 Saif-ur-Rehman Khan

    p12-6356 Haider Sajjad

    p12-6056 Shabab Iftikhar

    p12-6060 Akhwand Abdul Kareem

    p12-6006 Aizaz Sharif

  • Daniel

    I wrote the following code for three numbers:
    #include
    #include

    bool IsEqual(int x, int y, int z)
    {
    return (x == y == z); // this == is called the equality operator, it checks if something is equal
    }

    int main()
    {
    using namespace std;

    cout <> x;

    cout <> y;

    cout <> z;

    bool bEqual = IsEqual(x, y, z);
    if (bEqual)
    cout << x << " , " << y << " and " << z << " are equal" << endl;
    else
    cout << x << " , " << y << " and " << z << " are not equal" << endl;

    cin.clear();
    cin.ignore(255, '\n');
    cin.get();
    return 0;
    }

    the problem is unless the numbers are 1, 1, 1 are get false. Any advice???

  • hockey1scool

    My program will run but when i try to build it, it wont work. what does that mean?

  • Son_Of_Tesla3215

    Lol so here’s my little attempt at a bool comprehensive test for my self.

    #include “stdafx.h”
    #include

    int main()
    {
    using namespace std;
    cout << "Do you like taco's? Yes(1) No (0)" <> bYes;

    if (bYes == 1)
    cout << "Sweet ! tacos rule" << endl;
    else
    cout << "gay, you're gay" << endl;
    return 0 ;
    }#include "stdafx.h"
    #include

    int main()
    {
    using namespace std;
    cout << "Do you like taco's? Yes(1) No (0)" <> bYes;

    if (bYes == 1)
    cout << "Sweet ! tacos rule" << endl;
    else
    cout << "gay, you're gay" << endl;
    return 0 ;
    }

  • TheProgaminator

    Hey, I LOVE your tutorials, but what I want to know is, will you have more on how to program a game? Please Reply, Thanks

  • Kiran

    Thanks Ashish.. That helps!!!

You must be logged in to post a comment.