#include <cstdio>
int main()
{
bool l_default_value;
if(l_default_value)
printf("default value for bool is true\n");
else
printf("default value for bool is false\n");
return 0;
}
Is there a default value for a bool in C++? Why this happens?
TIA.
C++ Default value for bool
Hello everyone!
I always thought that the default value for a bool was false. But it turned out i discovered that it gets true sometimes, and it depends on the machine it is running.
No, primitives, including bool, are not guaranteed to be initialized to any particular value in the general case.
i see.
Don't know where/when i formed this idea about it. Glad i've run into this.
thanx SiCrane.
Don't know where/when i formed this idea about it. Glad i've run into this.
thanx SiCrane.
There are no default values in C++ for primitive types. You are just getting whatever happened in be in memory at that location. Debugger's will usually initialize stuff to default values.
Quote:Original post by filipe
I think bools are initialized to 0 if they're globals.
It would seem to apply for all globals then.
At least my combination of bools and ints all got zero as their initial values.
Or its just that, the whole datasegment is just by default zeroed?
This happened on Visual Studios debug mode though...
Wonder if enabling optimizations and disabling runtime checkups would alter the result.
Quote:I think bools are initialized to 0 if they're globals.
Under no circumstances would I recommend you ever rely on this being the case.
Quote:
Under no circumstances would I recommend you ever rely on this being the case.
It is reliable; objects with static storage duration are zero-initialized before all other initialization occurs (see 'basic.start.init' in the standard).
Only for certain values of "reliable" though. Try running this with MSVC 2008:
I'm firmly in the "just initialize your variables" camp.
struct Foo {};int Foo::* data;int main() { std::cout << (data == 0) << std::endl;}
I'm firmly in the "just initialize your variables" camp.
Just don't be lazy, if you need something initialized to a particular value, do it explicitly yourself, it really isn't that much of a deal to write:
instead of
or is it?
bool var = false;
instead of
bool var;
or is it?
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement