Khay Leng
Khay Leng

Reputation: 451

What does return alone does in C++?

I've been reading an example about finding gcd, which is Greatest Common Divisor, but it uses return only in the following code. What's it that? Is it legal to use return like that? I've searched about that and nothing seems to make me clear. Please.. Here's the code:

void fraction::lowterms ()
{
    long tnum, tden, temp, gcd;// num  = numerator and den = denumator 
    tnum = labs (num);
    tden = labs (den);
    if ( tden == 0)
    {
        exit (-1);
    }
    else if ( tnum == 0)
    {
        num = 0;
        den = 1;
        return; //why return alone    used here???
    }
}

Upvotes: 3

Views: 1124

Answers (5)

MKR Harsha
MKR Harsha

Reputation: 115

return is mostly used to return back to your caller function. It won't execute the below instructions in your function.

Ex:

void disp()
{
    1.....
    2.....
    return
    3....
    4....
}

here it won't execute 3 and 4 isntructions.

Upvotes: 0

Youka
Youka

Reputation: 2715

Every function returns to the caller (more exactly the command after the call) at the end, so there's always a return, even in a function with return type void (where the compiler appends return; to the body, the programmer doesn't have to care about it). With your manual inserted return you created another exit point for your function.

Upvotes: 0

edmz
edmz

Reputation: 8492

If you find it more comfortable, you can

 return void();

which is equivalent to return; which may look misleading at first glance.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 118021

In this case, nothing except terminate the function (which would have happened anyway)

The return type of this function is void meaning it does not return any value.

However, in general, the return statement stops the function, returns the value specified, then no further code in that function executes. In this case it was at the end of the function, so it adds nothing.

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

It ends execution of the function and returns control to the part of code that called the function.

There is no value after the return keyword, because the function has a return type of void and thus there is simply no value to return.

As explained in your C++ book!

Upvotes: 3

Related Questions