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.
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.
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.
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.
3. What are the different ways to initialize an array with all elements as zero? Explanation: None.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With