help with returns

Can i return like that?

1
2
3
4
5
6
  int a,b;
  int sum(a, b)
  {
     sum = a+b;
   return 0;
  }


or only like this?

1
2
3
4
 int sum(int a, int b)
{
  return a+b;
}
Last edited on
If you actually want to know what the sum is, do the second.

At most, the first would return 0, but goodness knows what it does when you set the name of the function to something. Correct in Fortran; wrong in C++.
Last edited on
the first example has syntax issues. you can't define a function without types on the parameters.

the first example if you fixed this issue would always return zero. this is not likely what you want, but its legal, eg:

int sum(int a, int b)
{
return 0; //legal, but it isnt a sum ... this is what your first example looks like corrected and the do-nothing sum= statement removed.
}

the second example is correct, but it isnt the only way.
@erikas37 -- Strive for declaring variables as close as possible to the place you'll be using them (defining, assigning, changing, etc.)

A word you'll hear a lot is scope. A good practice is to limit the scope of everything as much as possible. Your first example is bad because a and b are declared globally, while really the only "guy" who cares about them is the sum() function. Make them local to the sum() function.

Similarly, in loops, don't declare indexing variables far in advance:
1
2
3
4
5
int i;
cout << "I'm going to do lots of stuff before my for loop!\n";
// ... lots of stuff ...
for (i=0; i<5; ++i)
    cout << i << ' ';


Instead make "i" local to the for loop, because other parts of the code don't care.
This is actually another popular concept in programming: treat other parts of the code on a Need-To-Know basis. Better practice:
1
2
3
4
cout << "I'm going to do lots of stuff, but I won't declare i in advance!\n";
// ... lots of stuff ...
for (int i=0; i<5; ++i)
    cout << i << ' ';
Topic archived. No new replies allowed.