+ 2
What is the benefit of return in calculation ? Please give code example in c++
Return in calculation
11 Réponses
+ 2
It returns the the values with you have done something
+ 2
This is a difference between imperative and procedural programming style.
Imperative means that you just write the commands in the program in specific order and the computer executes them line by line from begin to end.
Procedural means that you organize some parts of your program into 'functions' which you write only once, but can use several times in your program with different parameters. This is really useful if the function is just a little bit more complicated than adding two numbers.
+ 2
The examples at the link above have nothing to do with functions and "return": I suggested it just to show you the difference between a global (defined out of a function) and a local (defined inside a function) variable.
So, just to recapitulate, a function is like a subprogram inside the main program. You can do everything without using any function, or you can call a function without using "return" (for example just for printing).
But when you need to communicate the function results to the caller, the common method is using "return". There are also other methods anyway: modifying the values of global variables, or assigning input arguments passed by reference.
Programming is freedom...
+ 1
Can you give me code example please ?
+ 1
int sum(int a, int b)
{
return a + b;
}
+ 1
We can make it like this.
int a,b;
a+b
This what confuses me because instead of saying "return a+b "we can say a+b or
int sum=a+b
I'm still confused. Why should we use the return in this ?
+ 1
"This what confuses me because instead of saying "return a+b "we can say a+b or
int sum=a+b" The unknown 321
- saying a+b is not ok, because you do not assign your sum, and your value is lost
- saying int sum=a+b could be ok if sum is defined out of your function, but in that case
the function is said to have collateral effects. On the other hand, if sum is defined inside your function, the scope is local and the value is lost on exit
So return is like a temp assignment (assembly registry EAX), which pass the value to the caller.
0
"Saying int sum=a+b could be ok if sum is defined out of your function" what do you mean by this ?
0
please try if this can make sense to you:
https://www.tutorialspoint.com/Difference-between-static-auto-global-and-local-variable-in-Cplusplus
0
This was good but I didn't see they returned any result ?
Which means they didn't write return sum;
0
Why didn't they add return in there ?