Home > database >  Why does returning a vector initialized with curly braces within normal brackets cause a compilation
Why does returning a vector initialized with curly braces within normal brackets cause a compilation

Time:11-02

I just wrote a simple method to return a vector made with two int arguments. However, when I return the initialized int vector within normal brackets, it causes compilation error.

std::vector<int> getVec(int x, int y)
{
    return({x, y}); // This causes compile error
    return {x, y};  // This is fine
}

The error message says:

q.cpp: In function ‘std::vector<int> getVec(int, int)’:
q.cpp:8:21: error: expected ‘;’ before ‘}’ token
    8 |         return({x, y});
      |                     ^
      |                     ;
q.cpp:8:15: error: could not convert ‘((void)0, y)’ from ‘int’ to ‘std::vector<int>’
    8 |         return({x, y});
      |               ^~~~~~~~
      |               |
      |               int

CodePudding user response:

From return statement:

  • return expression(optional) ; (1)
  • return braced-init-list ; (2)

Remember the {..} has no type, and deduction or type can depend of context.

There is a special case for return {..} (2) and uses copy-list-initialization to construct the return value of the function.

In return ({x, y}), we go in (1), and {x, y} still has no type, no special cases for ({..}). So the error.

CodePudding user response:

return {x, y};

{x, y} is a std::initializer_list<int>, so when your compiler sees this, it can deduce the type into:

std::vector<int>{std::initializer_list<int>{x, y}};

But:

return ({x, y});

This isn't systax correct:

std::vector<int>({std::initializer_list<int>{x, y}});

The compiler doesn't know hơ to deduce this, so it gives a compilation error.

  • Related