Default value of dynamic bool array in C++ -
this question has answer here:
i need create bool array unknown length passed parameter. so, have following code:
void foo (int size) { bool *boolarray = new bool[size]; (int = 0; < size; i++) { if (!boolarray[i]) { cout << boolarray[i]; } } }
i thought boolean array initializing false values...
then, if run code in eclipse (on ubuntu), works fine me, function prints values because !boolarray[i] return true (but values not false values, garbage values). if run in visual studio, values garbage values too, function not print value (because !boolarray[i] returns false). why array values not false values default?!? , why !boolarray[i] returns false in visual studio returns true in eclipse?!?
i read question: set default value of dynamic array, if change code following, works fine me (in eclipse , in visual studio)! have no idea why.
void foo (int size) { bool *boolarray = new bool[size](); (int = 0; < size; i++) { if (!boolarray[i]) { cout << boolarray[i]; } } }
sorry bad english!
thanks in advance!
adding ()
pod instantiation, invokes value initialization in c++03 , later. in c++98 invoked default initialization. both reduce zero initialization pod types, , booleans 0 false.
e.g., if s
pod struct
, , have variable
s o;
then can 0 doing
o = s();
no need unsafe , ugly memset
.
by way, std::vector<bool>
higher level alternative raw array of bool
, due what's seen premature optimization has bit odd behavior: supports implementation each boolean value represented single bit, , dereferencing iterator doesn't give reference bool
1 might expect general std::vector
. better alternative e.g. std::vector<my_bool_enum>
, my_bool_enum
defined. or std::vector<char>
. ;-)
regarding
“and why
!boolarray[i]
returnsfalse
in visual studio returnstrue
in eclipse?!?”
it's visual c++ chooses efficiency, not initializing doesn't have to, while compiler used in eclipse (presumably g++) initialize though doesn't have , isn't requested do.
i prefer visual c++ behavior here 2 reasons:
a main idea in c++ you don't pay don't use, , visual c++ behavior here in line idea.
zero-initialization can give users false impression code works, when in fact it's not portable.
Comments
Post a Comment