tags:

views:

112

answers:

6

let's say there is a dummy struct called foo_boolen and contains some boolen values as below

struct fool_boolen {
bool b1;
bool b2;
};

then, if I defined a variable of fool_boolen without initializing, what will be default value of the boolen variable in it? true, false or just a ramdom value of the two.

+1  A: 

if you mean bool the initial value is unknown.

MBZ
it's known - either true or false, but undefined
Chris Bednarski
@Chris no, it's not even guaranteed that the bool has any value at all. It may contain a bitpattern that represents neither true nor false.
Johannes Schaub - litb
@Johannes: yeah, I read the answer that mentions the Standard after I wrote my comment. Would be interesting to find an architecture that makes this possible.
Chris Bednarski
+6  A: 

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.

Alexander Rafferty
A: 

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!

SepiDev
Did your compiler change your ` : ` to a `, `?
Default
+1  A: 

According to my understanding,

if u declare the object as global or static then the values should be initialized to false.

Otherwise the values are not initialized (basically could be either true/false).

aeh
@aeh: why it will be initizlized to false when it is declared as global or static?
Haiyuan Zhang
@Haiyuan: The Standard says "objects with static or thread storage duration are zero-initialized".
aeh
+1  A: 

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..

liaK
+7  A: 

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 unknown. 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.

KennyTM