1

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?

3
  • 1
    What are you really trying to do? Why are you using the ternary expression for this? Why can't you use plain assignment within a proper if ... else ...? Commented Jun 15, 2021 at 21:43
  • 1
    Try auto const vec = true ? std::vector<int>{3,4} : std::vector<int>{5}; Commented Jun 15, 2021 at 21:44
  • @Someprogrammerdude I was hoping for a one-liner code, didn't expect that line to throw up so many errors. Now I'm curious over what's happening Commented Jun 15, 2021 at 21:49

1 Answer 1

2

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 } }; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.