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

From Standard docs, 3.9.1.6.

Values of type bool are either true or false.47)

47)

Using a bool value in ways described by this International Standard as “undefined,” such as by examining the value of an uninitialized automatic variable, might cause it to behave as if it is neither true nor false.

So, it is undefined..


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.


It will produce random numbers, Why? because i tested it with g++:

#include <iostream>

using namespace std;

struct fool_bool
{ 
    bool a;
bool b;
};

int main(int argc, char **argv)
{
fool_bool fb1;
cout << fb1.a << " : " << fb1.b << endl;
}

the first test showed me 121, 235 and the second one showed me, 34, 331 so it will be easy to figure it out!


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.

Tags:

C++