Home >Backend Development >C++ >How Can I Initialize All Elements of a C Array to a Specific Non-Zero Value?
Initialization of Arrays to a Default Value in C
When initializing arrays in C , using the syntax int array[100] = {-1}; sets only the first element to the specified value, while the remaining elements are initialized to 0. This is because the syntax {
To initialize all elements to a specific non-zero value, such as -1, the std::fill_n function from the
std::fill_n(array, 100, -1);
Alternatively, in portable C without the std::fill_n function, a loop can be used:
for (int i = 0; i < 100; i++) { array[i] = -1; }
Regarding performance, initializing the array with a non-zero value through the std::fill_n function or a loop does not have a significant performance difference compared to using the {
The above is the detailed content of How Can I 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!