Athul
Athul

Reputation: 449

Function to find largest number

I'm learning C++ through Sololearn. Below is a code to find the largest of two numbers.

#include <iostream>
using namespace std;

int max(int a, int b){

   if (a > b) {
       return a;
   }

   return b;
} 

int main() {

    cout << max(7, 4) << endl;
    return 0;
}

Result - 7

But shouldn't it return b also since there's return b in function????

Upvotes: 6

Views: 11847

Answers (5)

grindaah
grindaah

Reputation: 41

Operator return will

terminate the current function and returns the result of the expression to the caller

http://en.cppreference.com/w/cpp/language/return

After you passed the condition

if (a>b)

edited -> thanks to athul return will evaluate a and put it as result of function.

If a is lesser then b - you will not meet this condition and you will hit

return b;

To understand it, you may add:

cout << max(2, 4) << endl;
cout << max(2, 1) << endl;

into the main section.

PS it is better to use at least codeblocks, which is advised in LearnC++ to enter their examples

Upvotes: 2

Jacques de Hooge
Jacques de Hooge

Reputation: 6990

The answer of CoryKramer says it all. Still, to avoid the confusion you bumped into, I would prefer:

#include <iostream>
using namespace std;

int max(int a, int b){

   if (a > b) {
       return a;
   }
   else {
       return b;
   }
} 

int main() {

    cout << max(7, 4) << endl;
    return 0;
}

Alternatively you could use:

return a > b ? a : b;

The latter line is a so called 'conditional expression' (or 'conditional operator'). If the phrase before the ? is true, it returns the part between the ? and the :, else it returns the part after the : .

It is explained in detail here.

Upvotes: 5

user6585842
user6585842

Reputation:

You can use in return a > b ? a : b operator.

Upvotes: 2

chex
chex

Reputation: 249

if (a > b) (7>4) ==> Condition becomes True so return a executed and max function return from there only, its not reach to return b, that's why its not execute return b.

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

Only one return statement will execute within a function. As soon as the code encounters the first return it will immediately leave the function and no further code will execute.

Upvotes: 9

Related Questions