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????
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With