Dave's Brain

Browse - Programming Tips - What is a fast way to initialize a bool array ?

Date: 2014oct23
Language: C/C++

Q.  What is a fast way to initialize a bool array ?

A.  For true or false you can use memset().  Often the compiler can
turn that into a single machine instruction.

#include <stdio.h> #include <string.h> // memset() is here main() { const int MY_SIZE = 1000; bool a[MY_SIZE]; // 1. naive way - works but not super fast for (int i = 0; i < MY_SIZE; i++) { a[i] = true; } // 2. using memset memset(a, true, sizeof(a)); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.