Page 1 of 1

C++ bools

Posted: Mon Feb 13, 2006 6:10 am
by Neo
One quick C++ question.
If we declare a bool is it by default initialized to some value? (false or true).
If not what is it n majority of the cases from your experience? :)
TIA

Re:C++ bools

Posted: Mon Feb 13, 2006 6:22 am
by Solar
Neo wrote: One quick C++ question.
There are two, but I will forgive you this little bug. ;-)
If we declare a bool is it by default initialized to some value? (false or true).
To quote from Stroustrup's book "The C++ Programming Language":
If no initializer is given, a global object, a namespaced object, or a local static object is initialized with a 0 of the appropriate type.

[...]

Local variables (sometimes called automatic objects) and objects created on the heap are not initialized by default.

[...]

Elements of arrays and structures are initialized with the default, depending on whether they are static or not.
Read, if they are initialized, they are initialized to zero (false). But as sometimes they are not initialized, it is very wise to initialize them always to a value of your choosing.
If not what is it n majority of the cases from your experience? :)
I shudder even thinking anybody might answer this, or worse, you actually acting on such "knowledge"... one of the 10 Commandments of Programming: Do not assume. Define, assert, document, but never assume something that is not documented.

Re:C++ bools

Posted: Mon Feb 13, 2006 6:33 am
by Neo
Solar wrote: I shudder even thinking anybody might answer this, or worse, you actually acting on such "knowledge"... one of the 10 Commandments of Programming: Do not assume. Define, assert, document, but never assume something that is not documented.
Nope you got me wrong there. I explicitly initialized it to "false" as well as made a few other minor changes elsewere in some code I'm looking at and it's crashing now.
So I was just wondering if maybe it was assumed to be true earlier. :)

Re:C++ bools

Posted: Mon Feb 13, 2006 6:52 am
by Solar
To sum it up in one punch line: Zero or undefined.

As bools are usually stored as int, and any other value than zero is "true", "undefined" equates "true" with a probability of 1 : 2**32-2. ;)

If I were you, I would roll back the changes (you are using some version control software, aren't you?) and add a couple of assert()'s to check whether those bools are true or false if you don't initialize them.

Re:C++ bools

Posted: Tue Feb 14, 2006 2:38 am
by Neo
Yup did that works ok now. :)