Early Return

Hello all,
I would like to understand more about the early returns… Here’s my issue.

if ( Cond a )
{
if( Cond a.1 )
{
“code a.1”
}
else
{
“code a.2”
}
}
else
{
“code b”
}

How does early return functions? and what does it return?.. how does it skip through if statements?

for example if I try to simplify the code.

if ( !Cond a )
{
“code b”
return;
}

if ( Cond a.1 )
{
“code a.1”
return;
}

“code a.2”

Are those 2 even the same?

1 Like

Hello!
First of all, you can either use the “</>” option to format the code you want to write, or just screenshot it, because it is difficult to read.

Now for your question, the two pieces of code will behave exactly the same. If “Cond a” is not true, then don’t bother to even go through the rest of it, just do “code b”. If it is true, then check for “cond a.1” and do the rest.

Both examples work the same, with the latter being a little more simplified.
Return, will resume the program from where the function was called. What it returns, depends on the function type. Is your function of type void? Then it returns nothing, it just exits the function. Is it int? Then return a number like 0 or 1 and use them to see if the “Cond a” was indeed true or not.

void Mike() 
{
    if (!Cond a)
    {
        code b
        return; //exits function, returns NOTHING
    } 
    else if (Cond a.1) //The program will go here if Cond a is true, so I am using "else if" instead of "if"
    {
        code a.1
        return; //Same as above
    }

    code a.2
}

Hope it helps.

1 Like

Thanks for the reply it demonstrated clearly the solution to my problem and sorry for the code, When I posted I totally forgot the marks while typing. It appears that I forgot I was in a void function and return just goes out of the function how stupid of me xD…

1 Like

You are very welcome! We always miss the most obvious sometimes

P.S. when you check for both “Cond a” and “Cond a.1”, you can just say
if(Cond a && Cond a.1) and then execute code a.1. Since both conditions must be true in order to execute code a.1, then we only need one “if” statement with both conditions in.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms