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
C++ bools
Re:C++ bools
There are two, but I will forgive you this little bug.Neo wrote: One quick C++ question.
To quote from Stroustrup's book "The C++ Programming Language":If we declare a bool is it by default initialized to some value? (false or true).
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 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.
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.If not what is it n majority of the cases from your experience?
Every good solution is obvious once you've found it.
Re:C++ bools
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.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.
So I was just wondering if maybe it was assumed to be true earlier.
Only Human
Re:C++ bools
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.
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.
Every good solution is obvious once you've found it.