return statement

When and why do we sometimes return a variable instead of 0?
How much is a+b?

Lets pretend that there is no operator+ and we have to use a function.
Lets call it 'sum'. The 'sum' shall compute the sum of two values.
Lets use it:
c = sum( a, b );
Can we do that?
Can a function return a value that we can store to variable 'c'?

If we cannot do that, then how do we get the result from the function?
Thanks so much! so we return c in that case right?
No.

Lets look at the implementation of sum():
1
2
3
4
5
6
Foo sum( const Foo& lhs, const Foo& rhs )
{
  Foo result = lhs;
  // somehow add rhs to the result
  return result;
}

(The Foo is some type.)

Then we use the function:
1
2
3
4
5
Foo a;
Foo b;
Foo c;
// set values of a and b
c = sum( a, b );


What we return from the function depends on what is/has the value that the function must return.


You have probably seen return 0; in function main(). The main() should return a small (preferably < 128) non-negative integer. If the value is 0, it is interpreted as success. All other values are error codes that can tell how the program failed.
Ok so I got this somehow but then, why can't I return c in this case c = sum( a, b );
Isn't c the result of a+b?
You have code in a function.
Within code you have variable named 'c'.
The 'c' has some value.

You ask whether you can return the c from the function?
Is the function supposed to return a value of the same type as the c is?
I feel a bit stupid now. There are some things that I just miss without a reason. thanks dude
Topic archived. No new replies allowed.