Declare a variable and return it in the same line C++

Viewed 501

I have code that does

if(x>5){
vector<int> a;
return a;
}

But i'm curious if theres a way to do this return in one line such like:

if(x>5){
return vector<int> a;
}
3 Answers

This will work as expected:

return vector<int>();

This creates an object and returns one at the same time. Since the object has not been created without any name, it is known as anonymous object.

Hence you can modify your code, without assigning a name to the variable, like this:

if(x>5){
return vector<int>();
}

The problem is that vector<int> a just creates an object but does not return anything, while vector<int>() returns the "anonymous" new object.

Try:

return vector<int>();

You can do:

return {};

This will create a anonymous object.

Related