• 0

Initialize Array of Boolean Values


Question

primitive bool variables have "false" by default.

Is there a better way of initializing an array of boolean value to "true"?

Normally this is the way :

for(int i = 0; i < n; i++) array = true;

Is there a way say, during declaration

bool array[10000] = {false};

and have all 10000 initialized to false without using the for loop?

Link to comment
https://www.neowin.net/forum/topic/278351-initialize-array-of-boolean-values/
Share on other sites

12 answers to this question

Recommended Posts

  • 0

Although you can't initialize them all to true, you can treat them all as true. Just do everything opposite in boolean statements, if that couple of seconds of runtime is that important to you. Btw, what in the world would you need a size 10000 boolean array for anyway?

  • 0
  Andareed said:
bool array[10000];

memset(&array, 0, 10000 * sizeof(bool));

585385868[/snapback]

Actually that should be memset(&array,1,10000*sizeof(bool)) if he wants true. Interesting way of doing it though, I didn't think of doing it that way, although it might not be anymore efficient than a loop anyways.

  • 0
  Citrusmoose said:
Although you can't initialize them all to true, you can treat them all as true.  Just do everything opposite in boolean statements, if that couple of seconds of runtime is that important to you.  Btw, what in the world would you need a size 10000 boolean array for anyway?

585385419[/snapback]

its theoretical i was just wondering. :)

i prefer to not do opposites for readability's sake.

  • 0
  Quote
Doesn't bool array[10000] = {true}; work too?

Doesn't work because it sets the first element to true and the rest gets initialized to 0, thus false.

You could try a

bool array[10000];
std::memset(array,static_cast&lt;unsigned int&gt;(-1), sizeof(array));

Or consider using a std::vector<bool> or std::bitset.

  • 0
  juan said:
if i understand correctly, the only way of initializing arrays on the stack is to use a loop. memset for heap.

585388902[/snapback]

No. memset doesn't care how you allocate memory. You can call memset on any value that has a memory address (e.g. ints, bools, bool arrays, int arrays, class objects, array of class objects, etc). That's also why memset is dangerous.

  Quote
Or consider using a std::vector<bool> or std::bitset.

++

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.