Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is bool in C++?

Tags:

c++

boolean

I ran across some very interesting code that makes me wonder about what bool is. I've always considered it to be a primitive type, like int or char or long. But today, I saw something that looked like this:

void boolPtrTest()
{
    bool thisBool = true;

    boolPtrHere(thisBool);

    printf("thisBool is %s\n", thisBool ? "true" : "false");
}

void boolPtrHere(bool& theBool)
{
    theBool = false; // uhh, dereferencing anyone?
}

And this code runs - no errors - and prints "thisBool is false"!

To further make this odd, I ran the following code:

bool myBool = new bool();

...and the code ran fine!

Before you go and downvote me for asking a "noobish" question

Here's my question: what is bool? Is it defined on an implementation-by-implementation basis? From the evidence shown above, I would say that it's a class. From a practical standpoint (disregarding the above), it would also seem proper to define a bool as a typedef to an int / char or have it #define'd. But how does one know what it is, (which would affect how you would treat it)?

EDIT: I thought I'd add that I'm working in VS 2008.

like image 744
adam_0 Avatar asked Jul 16 '10 23:07

adam_0


People also ask

What is bool used for in C?

A boolean is a data type in the C Standard Library which can store true or false . Every non-zero value corresponds to true while 0 corresponds to false . The boolean works as it does in C++.

Is bool there in C?

The C99 standard for C language supports bool variables. Unlike C++, where no header file is needed to use bool, a header file “stdbool.

Why is bool used?

We can use bool type variables or values true and false in mathematical expressions also. For instance, int x = false + true + 6; is valid and the expression on right will evaluate to 7 as false has value 0 and true will have value 1.

Does C use bool or boolean?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.


1 Answers

I just don't see the "weirdness" you describe.

You declare a bool, initialized to true. By calling a function and passing it by reference, you change its value to false.

Then you print out the value, and it works. What is the problem? More precisely, what is the evidence that something strange is happening?

Since you want to know the details, bool is probably either a byte(char) or an int. When you assign it true/false, it gets the values 0 or 1. (use sizeof and printf("%d") to examine it).

I suspect the real issue is that you don't understand the pass-by-reference of boolPtrHere. You are not passing a pointer to the bool. You are passing the actual value by memory reference. (think of it as a pointer that you do not need to de-reference).

like image 111
abelenky Avatar answered Sep 30 '22 16:09

abelenky