Return statements (Help)

Hello,

Before starting explaining what's my problem, thanks to the website's owner and thanks for his awesome book (Jumping into C++).

So this is my problem:
I can hardly understand the return statements, return 0; I can understand that "Tells the operating system that everything is ok";

What about return 1; in Functions? Can you explain to me nooby friendly?
No hard English please haha :(

Edit and oh:

1
2
3
4
int add(int x, int y)
{
return x + y;
}


I can understand the meaning, but why do you need the return statement?

Thanks for the support,
Jader.
Last edited on
I can hardly understand the return statements, return 0; I can understand that "Tells the operating system that everything is ok";


Put this out of your head. This will confuse you. Return values have nothing to do with telling the OS anything. main's return value is a special case.


A return value very simply is a function's output. This output can be assigned to a variable. A simple case of this:

1
2
3
4
5
6
7
8
9
int giveMeFive()  // <- the return type is an 'int'
{
  return 5;  // the return value is 5, which is an 'int'
}

int main()
{
  int foo = giveMeFive();  // foo is now == 5
}


By assigning a function call to some variable, the function name evaluates to it's return value. That's overly wordy... but basically all it means is that when you say:
int foo = giveMeFive();

You are assigning whatever 'giveMeFive' returns to the 'foo' variable. Since in this case, giveMeFive returned 5... foo will be assigned the value of 5.




EDIT:

A slightly more complex example:

1
2
3
4
5
6
7
8
9
int add( int a, int b )  // a function which adds two numbers and returns the sum
{
  return a + b;
}

int main()
{
  int foo = add( 4, 8 );  // foo == 12
}


Here, add will take the given 4,8 values, and add them, returning the result (12). Since the return value is 12, that gets assigned to foo, so ultimately foo == 12.


EDIT2: hah, you posted the add example XD I didn't see that.
Last edited on
Topic archived. No new replies allowed.