1

Mac g++ throws a compilation error with this code:

#include <iostream>

using namespace std;

int main(int argc, char ** argv) {
    int * p = new int[5] {1,2,3};
    return 0;
}

I tried an online compiler and it compiles and runs without errors.

Is there something wrong with mac compiler? Can I do something to change how it works or should I install another c++ compiler?

Edit:

The error:

test.cpp:6:25: error: expected ';' at end of declaration
    int * p = new int[5] {1,2,3};

Compiler target and version:

Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0

Compile command:

g++ test.cpp 
  • 1
    Seems totally fine on [trunk](https://godbolt.org/z/jq84KG). What's the error? – George Jan 31 '21 at 14:41
  • 1
    The only way I can think of getting that error with `clang` is if you're compiling with something like `-std=c++03`. Can you provide the compile command used? – G.M. Jan 31 '21 at 14:46
  • 1
    Feels like a likely explanation, I get the same [error](https://godbolt.org/z/8rjdve) using with the op's compiler using C++03. – George Jan 31 '21 at 14:48
  • I ran https://stackoverflow.com/a/51536462/8138251 and got C++98. – Diego Salas Jan 31 '21 at 14:49
  • 1
    Try adding `-std=c++11` to your command line, the aggregate initialization syntax is a C++11 feature. – George Jan 31 '21 at 14:52
  • This (-std=c++11) worked, thanks. Should be an answer instead of a comment so I can mark my question as answered. – Diego Salas Jan 31 '21 at 14:54

1 Answers1

3

There's no fundamental reason not to allow a more complicated initializer it's just that C++03 didn't have a grammar construct for it. In the next version of C++, you will be able to do something like this. int* p = new int[5] {0, 1, 2, 3, 4};

You can try adding -std=c++11 to your command line and that should be working all fine.

Tan Yi Jing
  • 295
  • 1
  • 8