1

I am doing the following:

double dVar[100] = { 0.1 };

But when I debug, it only puts 0.1 to dVar[0] and rest are all 0.0;

I just thought to avoid a for loop.

Can someone please help me?

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
chintan s
  • 6,170
  • 16
  • 53
  • 86

2 Answers2

4

But when I debug, it only puts 0.1 to dVar[0] and rest are all 0.0;

This is the expected behaviour. If the initializer contains less elements than the aggregate (the array) then value-initialization is performed on the remaining elements, which in this case sets them to zero.

While not initialization, to avoid explicitly hand-coding a loop use std::fill():

double dVar[100];
std::fill(std::begin(dVar), std::end(dVar), 0.1);

As suggested by Olaf Dietsche in his answer, changing from an array to a std::vector<double> would permit initialization to a value other than zero. If the fact that the std::vector can change size is unappealling and your compiler has some c++14 features you may want to consider using std::dynarray. It is not possible to change the number of elements in a dynarray and all elements can be assigned a value other than zero at initialization, similar to std::vector:

std::dynarray<double> dVar(100, 0.1);
Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
4

This is expected behaviour. If you don't initialize all elements of the array explicitly, they will be automatically set to zero.

To initialize all elements to 0.1, you can use a std::vector and use a constructor with explicit initialization

std::vector dVar(100, 0.1);

This will create a vector with 100 elements, all set to 0.1.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198