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

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

Susan Sarandon
Release: 2024-12-28 22:03:11
Original
233 people have browsed it

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

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};
Copy after login

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:

  1. std::fill_n: Using the std::fill_n function from the library:
std::fill_n(array, 100, -1);
Copy after login
  1. Looping: In standard C , creating a loop to assign values to each element would be necessary:
for (int i = 0; i < 100; i++) {
  array[i] = -1;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template