function c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

function c++

Can someone explain to me how to use and when to use return in function ? for example:- #include <iostream> using namespace std; int larger(int,int); int main() { int num1,num2,bigger; cout<<" Enter integer one : "; cin>>num1; cout<<" Enter integer two : "; cin>>num2; bigger = larger(num1,num2); cout<<" The bigger number is: "<<bigger; return 0; } int larger(int no1,int no2) { int big; big = no1+no2; return big; //I can use this return or not. It doesn't matter } There's no different if I use return or not in the function. The output will be the same. I don't understand when to use it. Can someone explain it to me? Thank you for your time :)

3rd Jan 2019, 11:39 AM
Syed Bob
5 Answers
+ 4
Flowing off the end of a value-returning function (except main) without a return statement is "undefined behavior". _____ https://en.cppreference.com/w/cpp/language/return
3rd Jan 2019, 1:11 PM
Babak
Babak - avatar
+ 2
I cant see anything wrong with the code it works how i expected. You take 2 values from user function larger() is invoked and values are passed to the function added together and then returned which is then assigned to the variable bigger and printed to console?
3rd Jan 2019, 12:08 PM
D_Stark
D_Stark - avatar
0
What do you mean that there is no different if you return the value or no? If the fanction dont return any value, that is the fancution would be void, you will have no value assainged to the bigger variable and the output wont be correct...
3rd Jan 2019, 12:14 PM
Sekiro
Sekiro - avatar
0
I see, alright I get it. I just confused why do we need to put a return statement in function if it doesn’t have any difference whether we use it or not. But thank you so much everyone. Really help me a lot. Have a nice day ! :)
3rd Jan 2019, 1:26 PM
Syed Bob
0
I want posted comment in the code
3rd Jan 2019, 1:34 PM
Ḿổḩảḿḿẻď Ấḿiň
Ḿổḩảḿḿẻď Ấḿiň - avatar