mardi 2 novembre 2021

Why does returning a vector initialized with curly braces within normal brackets cause a compilation error?

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

Aucun commentaire:

Enregistrer un commentaire