0

Why can initialize array nums with parentheses, but cannot with braces? Whats the difference here? I know nums is variable sized object and cannot be initialized, but I am not sure why it can be initialized with zeros using parentheses.

This works:

int n = 5;
int nums[n]();

This doesn't:

int n = 5;
int nums[n]{};
jbapple
  • 3,297
  • 1
  • 24
  • 38
Comizard
  • 45
  • 4
  • I think you have what works and doesn't work round the wrong way. At least, the second works in **Standard** C++ if you make `n` into `const int n = 5;`. – Adrian Mole Apr 02 '22 at 19:18
  • Syntax matters: `int nums[5]{{}};` Also, VLAs are illegal in C++. – Dúthomhas Apr 02 '22 at 19:21
  • This brace initialization is perfectly valid. However the specification of the array with a non-constant `n` is not valid standard C++. – jkb Apr 02 '22 at 19:22
  • 3
    In the first, you are attempting to declare an array of functions returning `int`. – Adrian Mole Apr 02 '22 at 19:22
  • @Dúthomhas not illegal, just not ISO standard C++. – Taekahn Apr 02 '22 at 19:33
  • If I compile your code that "works", I get "error: declaration of 'nums' as array of functions". The declaration says "`nums[k]()` is an `int`". – molbdnilo Apr 02 '22 at 19:34
  • 3
    `int n = 5; int nuns[n];` is not standard C++. There's a lot of confusion because one compiler supports this as an extension but doesn't give (the required) warning. In any event, if your compiler allows a non-constant array dimension, you have to ask the implementors of that compiler for more details about what they did. – Pete Becker Apr 02 '22 at 19:51

0 Answers0