I notice a trend in your coding :) I noticed this on other projects that you've undertaken as well as your current "advanced calculator".
You have a habit of letting subroutines do output when they are calculating, separating calculations from output will make your subroutines easier to use and read. When I was a young man ;) we were always taught "Input/Process/Output" try not to mix these up.
eg;
1 2 3 4 5 6
|
int add ()
{
int num1, num2;
//...
cout << num1 + num2 << endl;
}
|
would be much better as
1 2 3 4 5 6
|
int add (int num1, int num2)
{
return num1 + num2;
}
cout << add(5,6) << endl;
|
The difference in your examples above is quite big.
cout is the console, so is cin. they are short for console in and console out. in BASIC they were PRINT and INPUT. reserve use of these until you actually want to see some results on the console.
In your second snippet above, the add routine doesnt actually do anything useful for the program, yes it adds the numbers but it doesnt do anything with the result other than send it to the console, so calling add() wont give the caller anything useful. Its more like a "PrintSum(int a, int b)" function.
Whats in a name? Lots to the reader, when naming functions try to name them so that the caller reads easy;
eg;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int GetValue(string prompt)
{
cout << prompt;
int val;
cin >> val;
return val;
}
int Add(int a, int b)
{
return a + b;
}
int main()
{
int x = GetValue("enter a number :");
int y = GetValue("and another :");
int z = Add(x,y);
cout << "Add() = " << z << endl;
}
|
The above code probably wont compile, its just to demonstrate the idea.
TheLoneWolf wrote: |
---|
So top one to give the value to main () ? |
No, any data coming out of a routine goes back to the caller, wherever that is. If you had called Add() from main() then yes, the return would send it there.
in the code below, Add() is called several times. When a function has a return statement, there is usually an assignment after the call so the return matches that.
in test() Add() will return 9 which is assigned to i.
in AnotherTest() Add() will return 4, which is assigned to j,
then test() will return 9 which is passed to Add() along with j. That Add() will return 13.
AnotherTest() will return the result of Add() (13) to whichever function called AnotherTest()
1 2 3 4 5 6 7 8 9 10 11 12
|
int test()
{
int i = Add(4,5);
return i;
}
int AnotherTest()
{
int j = Add(2,2);
return Add (j, test());
}
|