Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to find largest number

Tags:

c++

function

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????

like image 911
Athul Avatar asked Aug 03 '16 11:08

Athul


2 Answers

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.

like image 188
Cory Kramer Avatar answered Sep 26 '22 23:09

Cory Kramer


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.

like image 34
Jacques de Hooge Avatar answered Sep 26 '22 23:09

Jacques de Hooge