Initialization of All Array Elements to a Default Value
In C , you can initialize all elements of an array to a default value using the following syntax:
int array[100] = {0};
This will set all elements of the array to 0. However, you may encounter unexpected behavior when attempting to initialize all elements to a non-zero value, such as -1.
Setting All Elements to a Non-Zero Value
The syntax:
int array[100] = {-1};
instructs the compiler to set only the first element to -1, while the remaining elements will default to 0. To initialize all elements to -1, you can use methods like:
std::fill_n(array, 100, -1);
for (int i = 0; i < 100; i++) { array[i] = -1; }
Performance Consideration
Whether default initialization is faster than a loop-based approach depends on factors such as the compiler and the target platform. In general, modern compilers can optimize away loop-based initialization by using platform-specific intrinsics. Therefore, the performance difference is often negligible.
The above is the detailed content of How to Efficiently Initialize All Array Elements to a Default Value in C ?. For more information, please follow other related articles on the PHP Chinese website!