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 
6
  • 1
    Seems totally fine on trunk. What's the error? Commented Jan 31, 2021 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? Commented Jan 31, 2021 at 14:46
  • 1
    Feels like a likely explanation, I get the same error using with the op's compiler using C++03. Commented Jan 31, 2021 at 14:48
  • I ran stackoverflow.com/a/51536462/8138251 and got C++98. Commented Jan 31, 2021 at 14:49
  • 1
    Try adding -std=c++11 to your command line, the aggregate initialization syntax is a C++11 feature. Commented Jan 31, 2021 at 14:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.