Understanding Array Initialization in C
The topic of array initialization in C can be confusing, especially when attempting to initialize all elements to a non-zero default value. In this article, we'll address common questions and provide solutions for effective array initialization.
Initial Value Setting
In the given code:
int array[100] = {-1};
The expectation is for all elements to be initialized to -1. However, only the first element is set to -1; the remaining elements are initialized to 0 with some random values. This is because the omitted elements are implicitly set to 0.
To initialize all elements to -1, the correct syntax is:
int array[100] = {-1, -1, -1, ...};
or you can use the std::fill_n function from the
std::fill_n(array, 100, -1);
Performance Comparison
The default initialization method (int array[100] = {-1};) and the std::fill_n method both perform array initialization efficiently. While the default initialization may seem quicker, it's important to note that it can be implementation-dependent and not guaranteed to be faster in all cases.
For larger arrays, the std::fill_n method is generally more efficient as it avoids creating temporary variables for each element assignment.
The above is the detailed content of How Can I Efficiently Initialize All Elements of a C Array to a Non-Zero Value?. For more information, please follow other related articles on the PHP Chinese website!