Home > Mobile >  Declare a variable and return it in the same line C
Declare a variable and return it in the same line C

Time:11-19

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;
}

CodePudding user response:

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>();
}

CodePudding user response:

You can do:

return {};

This will create a anonymous object.

CodePudding user response:

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>();
  • Related