Initializing a primitive array to a single value

Is there a way to initialize an array of primitives, like an integer array, to 0? Without using a for loop? Search for short code that does not include a for loop.

:)

+6
c ++ integer primitive-types zero
source share
6 answers
int array[10] = {}; // to 0 std::fill(array, array + 10, x); // to x 

Please note if you want a more general way:

 template <typename T, size_t N> T* endof(T (&pArray)[N]) { return &pArray[0] + N; } 

To obtain:

 std::fill(array, endof(array), x); // to x (no explicit size) 

It should be mentioned that std::fill is just a wrapper around the loop you are trying to avoid, and = {}; can be implemented in such terms.

+17
source share

Yes it is possible. The initialization method depends on the context.

If you declare a static or local array, use = {} initializer

 int a[100] = {}; // all zeros 

If you create an array with new[] , use () initializer

 int *a = new int[100](); // all zeros 

If you initialize a non-static array of elements in the list of constructor initializers, use () initializer

 class C { int a[100]; C() : a() // all zeros { ... } }; 
+9
source share

You can use memset if you want all your values ​​to be zero. In addition, if you only want to initialize zero, you can declare your array in such a way that it fits in the ZI memory section.

+1
source share

If the number is zero, you can also use memset (although this is more C-style):

 int a[100]; memset(a, 0, sizeof(a)); 
+1
source share

double A[10] = { value }; // initialize A to value double A[10] = { value }; // initialize A to value . I don’t remember whether to compile the value of a constant or not. will not work with automatic arrays

0
source share

There are ways to hide what you are doing with a different syntax, and this gives you other answers - std::fill, memset, ={} , etc. In the general case (excluding trick compilers like ZI), think about what you need to do with compiled code:

  • he needs to know where your memory runs the block / array;
  • he needs to set each element to block the value in turn;
  • you need to check if the end of the block has been reached.

In other words, there should be a cycle in a rather fundamental way.

0
source share

All Articles