Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 385
zeltath Avatar asked Nov 01 '25 23:11

zeltath


2 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>();
}
like image 188
Abhishek Dutt Avatar answered Nov 03 '25 14:11

Abhishek Dutt


You can do:

return {};

This will create a anonymous object.

like image 20
justANewb stands with Ukraine Avatar answered Nov 03 '25 13:11

justANewb stands with Ukraine