Initializing Elements of an Array to a Default Value in C
The question arises from an array initialization in C using the syntax:
int array[100] = {-1};
This initialization sets the first element to -1 and leaves the remaining elements at 0, which isn't the desired behavior. To address this, the following points need consideration:
Syntax Interpretation
The syntax int array[100] = {-1}; essentially says, "set the first element to -1, and the rest to 0." When elements are omitted in an array declaration, they are automatically initialized to 0 by default.
Setting All Elements to a Non-Zero Value
To initialize all elements to a non-zero value like -1, one cannot rely solely on the default omitted value initialization. Instead, the following approaches can be used:
std::fill_n(array, 100, -1);
for (int i = 0; i < 100; i++) { array[i] = -1; }
Speed Comparison
The speed of default initialization compared to a loop is not significantly different. Both approaches initialize elements sequentially, so the time complexity remains the same. However, using std::fill_n can save a few instructions compared to a manual loop, making it slightly faster in most cases.
The above is the detailed content of How to Initialize All Elements of a C Array to a Specific Non-Zero Value?. For more information, please follow other related articles on the PHP Chinese website!