Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize all the elements of an array to the same number

Some time ago my old teacher posted this code saying that it is another way to initialize an array to the same number (other than zero of course).

Three in this case.

He said that this way is slightly better than the for loop. Why do I need the left shift operator? Why do I need another array of long? I don't understand anything what's happening here.

int main() {      short int A[100];      long int v = 3;     v = (v << 16) + 3;     v = (v << 16) + 3;     v = (v << 16) + 3;     long *B = (long*)A;      for(int i=0; i<25; i++)         B[i] = v;      cout << endl;     print(A,100); } 
like image 491
Cimmerian_Perspective Avatar asked Oct 06 '17 07:10

Cimmerian_Perspective


People also ask

How do you initialize an entire array with the same value?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

How do you initialize an array with all elements?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

How do you initialize an array to a number?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.


1 Answers

There are many ways to fill an array with the same value, and if you are concerned about performance then you need to measure.

C++ has a dedicated function for filling an array with a value, and I would use this (after #include <algorithm> and #include <iterator>):

std::fill(std::begin(A), std::end(A), 3); 

You shouldn't underestimate what optimizing compilers can do with something like this.

If you are interested in seeing what the compiler does, then Matt Godbolt's Compiler Explorer is a very good tool if you're prepared to learn a little bit of assembler. As you can see from here, compilers can optimize the fill call to twelve (and a bit) 128-bit stores with any loops unrolled. Because compilers have knowledge of the target environment they can do this without encoding any target-specific assumptions in the source code.

like image 57
CB Bailey Avatar answered Sep 21 '22 18:09

CB Bailey