Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize array with extra element using a macro

I am initializing an array in two different ways depending a macro:

# if feature_enabled
const int v[4] = {1, 2, 3, 4};
#else
const int v[5] = {0, 1, 2, 3, 4};
#endif

The problem is that the data in the assignment is actually large matrices, and for various reasons it's not a good solution to just copy the data with a minor modification (just one more element at the beginning of the array.)

I was wondering if there is a way to do the same thing that I did here, without essentially duplicating the last n-1 elements.

like image 375
C. E. Avatar asked Dec 06 '19 14:12

C. E.


People also ask

How do you initialize an entire array with value?

int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index. The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.

How do you initialize all elements of an array to 0 in C++?

The entire array can be initialized to zero very simply. This is shown below. int arr[10] = {0}; However, it is not possible to initialize the entire array to a non-zero value using the above method.

How do you initialize a dynamic array to zero?

So either use a vector or allocate the memory dynamically (which is what std::vector does internally): int* arrayMain = new int[arraySize-1] (); Note the () at the end - it's used to value-initialize the elements, so the array will have its elements set to 0. Save this answer.

What are the different ways to initialize an array with all elements as zero?

3. What are the different ways to initialize an array with all elements as zero? Explanation: None.


1 Answers

If you don't specify the size on the array but let it be auto-deduced, you can just add the 0 in the front conditionally:

const int v[] = {
# if feature_enabled
  0,
#endif
  1, 2, 3, 4
};
like image 165
Turtlefight Avatar answered Oct 03 '22 08:10

Turtlefight