Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of an unset boolean in C++? [duplicate]

Tags:

Possible Duplicate:
Why is a C++ bool var true by default?

Say I were to do something like this:

class blah {   public:   bool exampleVar; };  blah exampleArray[4]; exampleArray[1].exampleVar = true; 

In exampleArray, there are now 3 unset instances of exampleVar, what are their default values without me setting them?

like image 275
Lemmons Avatar asked Oct 23 '11 02:10

Lemmons


People also ask

What is the default value of boolean in C?

The default value of the bool type is false .

How do you set a boolean value true by default?

Use the create() or update() methods to specify the value of the new property as its default value, that is, false for boolean or 0 for integer.

What is the default value of a nullable bool?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns 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.


1 Answers

The default value depends on the scope that exampleArray is declared in. If it is local to a function the values will be random, whatever values those stack locations happened to be at. If it is static or declared at file scope (global) the values will be zero initialized.

Here's a demonstration. If you need a member variable to have a deterministic value always initialize it in the constructor.

class blah {   public:   blah()    : exampleVar(false)   {}    bool exampleVar; }; 

EDIT:
The constructor in the above example is no longer necessary with C++11. Data members can be initialized within the class declaration itself.

class blah {   public:   bool exampleVar = false; }; 

This inline default value can be overridden by a user-defined constructor if desired.

like image 77
Praetorian Avatar answered Sep 24 '22 13:09

Praetorian