Home >Backend Development >C++ >How Can I Initialize All Elements of a C Array to a Specific Non-Zero Value?

How Can I Initialize All Elements of a C Array to a Specific Non-Zero Value?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 01:05:09565browse

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 {} initializes only the first element, leaving the rest to be initialized with default values.

To initialize all elements to a specific non-zero value, such as -1, the std::fill_n function from the header can be used:

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 {} syntax for a value of 0. In either case, the compiler optimizes the initialization process.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn