Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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???
    }
}
like image 300
Khay Leng Avatar asked Apr 25 '26 18:04

Khay Leng


2 Answers

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.

like image 169
Cory Kramer Avatar answered Apr 28 '26 08:04

Cory Kramer


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!

like image 31
Lightness Races in Orbit Avatar answered Apr 28 '26 08:04

Lightness Races in Orbit