SJC
SJC

Reputation: 25

Primary expression error when defining a vector with ternary operator

I have a simple code where I try to define a vector as one of two initializer lists using a ternary operator:

int main() {
    std::vector<int> const vec = true ? {3,4} : {5};
    for (int const item : vec) {
        cout << item << endl;
    }
    return 0;
}

But then I see the below primary-expression error:

tmp.cpp: In function ‘int main()’:
tmp.cpp:7:41: error: expected primary-expression before ‘{’ token
     std::vector<int> const vec = true ? {3,4} : {5};
                                         ^
tmp.cpp:7:41: error: expected ‘:’ before ‘{’ token
tmp.cpp:7:41: error: expected primary-expression before ‘{’ token
tmp.cpp:7:47: error: expected ‘,’ or ‘;’ before ‘:’ token
     std::vector<int> const vec = true ? {3,4} : {5};

I couldn't find anything relevant in either ternary operator or initializer list initialization. What am I missing here?

Upvotes: 1

Views: 576

Answers (1)

ShadowMitia
ShadowMitia

Reputation: 2533

Because you can't have braces in that context. If you look at cppreference on list initialization, you see that the case inside a ternary operator isn't defined. So it can't be parsed correctly and you get the error you have.

You'd have to use something like this :

std::vector<int> const vec{(true ? std::vector<int>{3, 4} : std::vector<int>{5})};

Which basically expands to:

  if (true) {
    vec = std::vector<int>{3, 4};
  } else {
    vec = std::vector<int> { 5 }
  };

Upvotes: 2

Related Questions