+ 3
function
#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
3 Respostas
+ 3
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.
+ 2
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.