Using function return in if statement
Hey,
Just wondering if using a function's return in an if statement for example is fine, or if it's something i should avoid doing and use a variable instead? I'm learning about function return values which is something i never bothered using.
void Start()
{
if(RandomBool())
{
//Do something;
}
}
bool RandomBool()
{
return Random.value > 0.5f ? true : false;
}
Thanks
Answer by Harinezumi · Jan 17, 2018 at 03:48 PM
Of course it is correct, this is a typical use of a function. Basically you will have an "invisible" variable that is created for the return of the function. This saves you some lines and memory allocation for a local variable (although it might be optimized away by the compiler). It can also be easier to read, for example if you have a function IsVisible()
, writing if (IsVisible())
is very easy to understand.
Thanks, that's exactly what i wanted to know, you should make your comment an answer so that i can choose it.
Answer by ransomink · Jan 17, 2018 at 03:29 PM
Did you test and see if it works? There's nothing wrong with it. No reason to create a variable only to return it on the next line...
Oh it does work, just making sure that it's a perfectly fine way to do things before i start using it a lot