Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what will be the default value of an uninitialized boolean value in c++

Tags:

c++

Suppose I have a struct called foo_boolean that contains some boolean values:

struct foo_boolean {
    bool b1;
    bool b2;
};

If I define a variable of type foo_boolean without initializing it, what will the default value of the member variables be? (i.e., true, false, or a random value of the two.)

like image 782
Haiyuan Zhang Avatar asked Oct 02 '10 10:10

Haiyuan Zhang


People also ask

What is the default value of Boolean in C?

The default value of the bool type is false .

Why is Boolean default value False?

If you declare as a primitive i.e. boolean. The value will be false by default if it's an instance variable (or class variable). If it's declared within a method you will still have to initialize it to either true or false, or there will be a compiler error.

Are booleans false by default C++?

The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as false). All the values stored in the array in the above program are garbage values and are not fixed.

What is Boolean initialized as?

To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becomes the integer 1, and false becomes the integer 0.


2 Answers

It depends on how you create it. If the struct is constructed by default-initialization e.g.

void foo () {
  fool_boolen x;   // <---

then the values will be undefined (bad things will happen if you read it before setting a value).

On the other hand, if the struct is constructed by value-initialization or zero-initialization e.g.

fool_boolen x;   // <--

void foo2 () {
  static fool_boolen y; // <--
  fool_boolen z = fool_boolen();  // <--

then the values will be zero, i.e. false.

like image 144
kennytm Avatar answered Sep 18 '22 03:09

kennytm


The value of the bool will is undefined. It will be whatever else was on the stack before it, which is sometimes zeroed out if nothing has used it previously.

But again, it is undefined, which means it can be either true or false.

If you need a default value, you can do:

struct fool_bool {
  bool b1;
  bool b2;
  fool_bool() {
    b1 = true;
    b2 = false;
  }
};

This makes b1 true by default, and b2 false.

like image 39
Alexander Rafferty Avatar answered Sep 18 '22 03:09

Alexander Rafferty