0

Let's say I have a 1D dynamic array, that I want to fill with fibonacci numbers.

User enters size as 15, so I want first 15 fibonacci numbers.

So my question is this:

int* arr = new int [size];

and this

int* arr = new int [size]{};  

What do {} do ?, and what is the difference ?

Community
  • 1
  • 1
  • https://en.cppreference.com/w/cpp/language/value_initialization – Thomas Sablik Jul 10 '20 at 11:31
  • 1
    The real answer is to use an `std::vector`, as you shouldn't have to write `new` or `delete` ever, and that ensures that all values within the allocated `.size()` are initialised. Beyond that, I'd ask (a) where did you see these 2 options of code and (b) do you have a C++ book that could explain such basics of syntax? – underscore_d Jul 10 '20 at 11:36

1 Answers1

1

Effectively the paranthesis version ensures that all values are initliazized (ints will be initialized to zero) while otherwise that array might be filled with memory garbage since it just gave you a memory block, not doing anything with it. As a result, the paranthesis version might be a tad slower but that will only matter if you call this very often or with megabyte large arrays.

Note that often in debug mode, you will get a clean array anyways.

More details: Using (or not using) parentheses when initializing an array ( whetehr it's () or {} does not matter in this case as both can be used for initializing types or classes that have no custom constructor).

AlexGeorg
  • 967
  • 1
  • 7
  • 16
  • So with {} it will set 15 zeros in memory , until they are replaced with actual values. So in other words parentheses are used to prevent an array being filled with garbage? – JzrLegendary Jul 10 '20 at 11:40
  • 1
    @JzrLegendary Exactly. By the way, the hint to use vectors is good. They are the safer way to approach dynamic arrays and they rarely cost performance. And well, the paranthesis do not prevent the garbage to exist in first place, but they prevent that you accidentally access it if you read a value from that array before assigning to it. – AlexGeorg Jul 10 '20 at 11:42