Function to find the largest number

I am learning C ++ through Sololearn. Below is the code to find the largest of the 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 b be returned in the same way as return b in the function ????

+6
source share
5 answers

Inside the function, only one return will be executed. As soon as the code encounters the first return , it will immediately leave this function and no further code will be executed.

+8
source

CoryKramer's answer says it all. However, to avoid the confusion you are facing, 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 can use:

 return a > b ? a : b; 

The last line is the so-called conditional expression (or "conditional statement"). If the phrase is before? right, does it return the part between? and :, otherwise it returns the part after :.

Explained in detail here .

+5
source

if (a > b) (7> 4) ==> The condition becomes True , so return a is satisfied, and the max function returns only from there, it is not reached to return b, so return b does not execute it.

+2
source

The operator will return

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

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

After the transfer of conditions

 if (a>b) 

edited → thanks athul return will evaluate a and put it as the result of the function.

If a is less, then b - you will not satisfy this condition, and you will click

 return b; 

To understand this, you can add:

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

in the main section.

PS it is better to use at least the code blocks that are recommended in Learn ++ for entering your examples

+2
source

Can you use return a> b? a: b .

+2
source

All Articles