1

(I apologize if I do not use terminology correctly or if I am asking an obvious question. I only recently started learning C++)

I've seen that the most examples online use the following way to initialize array container:

std::array<int,3> myarray = { 2, 16, 77 };

But I tried doing the following:

std::array<int,3> myarray;

myarray[0] = 2;
myarray[1] = 16;
myarray[2] = 77;

Seems to be working too. Is first method preferred over the second or is the second one simply incorrect?

user
  • 2,939
  • 5
  • 26
  • 39

3 Answers3

4

std::array<int,3> myarray = { 2, 16, 77 }; is superior:

  1. It's clearer

  2. myarray is never in an undefined state. With std::array<int,3> myarray;, the elements are default-initialised, which means uninitialised as the default initialisation for an int is to leave it uninitialised. So the behaviour on reading back elements prior to setting their values is undefined.

  3. It's possibly faster. (The compiler might optimise the second way you've done it to the first way).

Since C++11 I would regard the second way as being wrong.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I understand the first one is called aggregate-initialization, do you know what the second method is called? – user Feb 02 '16 at 13:48
  • @user Pecking as opposed to touch typing might be about right :) But in all seriousness - it has no dedicated name, because it's nothing specific. You're just assigning values to elements individually, overwriting prior values (if any). You initialize the variables for sure, and that's fine in itself, but I don't think there's really a name for it. It usually doesn't belong in modern C++ code anyway, so if you feel like naming it "it what should not be done" than that's certainly a pragmatic way to go about it :) There's an infinite amount of ways to write non-idiomatic code that will work OK. – Kuba hasn't forgotten Monica Jun 17 '20 at 00:06
2

Both methods are fine, and the result is exactly the same. However, the first method is preferred, because not only is it more compact in code, but also faster at runtime as the container's elements are set in the constructor rather than being set after the constructor is called. Note that the first method is only available in C++11 and later.

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
2

As you said, "Seems to be working too". That is usually a good indication of the fact that both methods are fine. The first is generally used if you know all the elements up front and they are constants. The second method is often used if the elements need to be calculated somehow. It is important to note that until you have made the assignment, the values should not be accessed since they will be undefined. The size of the array container is constant, but the elements are not. You are free to change them at any time as you are doing.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264