Is there an easy way to initialize the entire C/C++ array to -1?

Asked 2 years ago, Updated 2 years ago, 88 views

int array[100] = {0};

I heard that the entire silver element is set to zero, so I thought I just need to set one

int array[100] = {-1};

So the first element is minus 1, and the rest is zero. I don't want to turn the for door because it's separate from declaration and initialization, is there any other way?

initialization c++ c array default-value

2022-09-22 22:18

1 Answers

int array[100] = {-1};

This code doesn't initialize the entire array to -1 It means, "Please make only the first element in the array -1 and initialize all other unspecified elements to zero."

I'll write down the code that initializes the entire array to the same value because C and C++ are slightly different.

First of all, you can see [How to initialize the C array] for C language.

If you use GCC other than that,

int array[100] = { [0 ... 99] = -1 };

It's possible.

A typical code that can only be written in C++ is std::fill_n in the header.

std::fill_n(array, 100, -1);


2022-09-22 22:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.