Diego Salas
Diego Salas

Reputation: 25

C++ compiler throws error on dynamic array with default values

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 

Upvotes: 1

Views: 136

Answers (1)

Tan Yi Jing
Tan Yi Jing

Reputation: 303

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.

Upvotes: 3

Related Questions