#include <iostream> using namespace std; int sum(int x, int y ) { int z; z=x+y; return z; } int main() { int z; z= sum(30,20); cout<<"sum = "<<z<<"\n"; return 0; } now on this code 1-why should we but return z; 2-what is the difference between writing int z; z= sum(30,20); cout<<"sum = "<<z<<"\n"; or cout<<"sum = "<<sum (30,20)<<"\n"; i mean is there any difference between using any one of them


8/24/2019 12:45:49 PM

Mahmoud Hamed

3 Answers

New Answer


The return value is what your function sends back to the calling program. Without one there would be no result. You did not need to declare a variable in the sum() function. return (x + y); would do the job just as well. As far as your other two examples are concerned they are functionally equivalent. Declaring int z and assigning the result of the calculation is just a bit easier to read and understand. If the calculation was very long and complex it would be more difficult to understand if everything was crammed into the cout statement. It is always a good idea to break your code into smaller lines of easily understandable code. An optimising compiler will usually do a far more consistently better job of optimising the code than the average programmer can do.


As Martin Taylor said, the two codes are functionally equivalent. It's often a good idea to assign a variable to an expression rather than just copy/pasting the entire expression into a program. This makes the cout expression both hard to understand, and, in repetitive tasks requiring the sum() function, can make calculations redundant, especially when the previous and current arguments are the same. This results in processor time loss in time-sensitive programs. It would be faster in the long run to store the value in memory and re-use it than calculate it again.


If use sum(20,20) just once then there's no problem putting it directly in the cout statement, but if your gona use is it dozens of times....then you should assign it to a variable because you're risking a potential typo by repeatedly typing the same (potentially critical) code, plus... if you later decide the sum should be sum(50, 30) you only have to change it once.