C++ Default value for bool

Started by
15 comments, last by TinyGameDev 13 years, 10 months ago
Quote:Original post by Kwizatz
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:

bool var = false;


instead of

bool var;


or is it?
It is, when you have an array. (Real programmers probably cry in pain while reading this)
Advertisement
bool array[100] = {};
Quote:Original post by DevFred
bool array[100] = {};

bool* array = new bool[100]();
too...

In general, always initialize your variables, never just leave it up to the compiler (even for statics), because interpretations of the standard varies from compiler to compiler, and even version to version. Just spare yourself the hassle and initialize them yourself.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Quote:Original post by DevFred
bool array[100] = {};
Hmmm. I learn something new every day. Thanks guys!
Quote:Original post by pauls_1979
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.


afaik, this is something you can rely on. anything with static duration will be 0'd, guaranteed.

static int magic[32] = { 0, 1, 2, 3 };

will end up 01230000...
Quote:Original post by clashie
anything with static duration will be 0'd, guaranteed.

Quote:Original post by SiCrane
Try running this with MSVC 2008:
struct Foo {};int Foo::* data;int main() {  std::cout << (data == 0) << std::endl;}


Quote:
static int magic[32] = { 0, 1, 2, 3 };

will end up 01230000...

Which doesn't rely on the zero-initialization of objects with static storage duration. If you specify four items in an aggregate initializer list for an array of 32 ints, you aren't saying leave the items you didn't specify uninitialized, you're saying initialize the rest of the other items with 0.
Uninitialized statics are stored in the .bss section of the program and the loader knows to initialize these variables to 0. However, if the static is actually placed in the .bss section might be compiler specific so to be safe you should probably just initialize it yourself.

Making Terralysia, wishlist now on Steam <3!

This topic is closed to new replies.

Advertisement