Returns help!

Help me understand Return statements. Basically all they do is when you end the function it will do whatever the return statement is?
Like, for the main function, return "0" is code for kill the program?

And in the function below pizza_value, it will return (or print out?) a value of 8 when I call it in the main function?

So is it sorta kind of like a variable that holds a value or information?

Thanks in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int pizza_value();

int main()
{
cout << "$" << pizza_value();

return 0;
}

pizza_value()
{
return 5+3;
}
The function call "evaluates" to whatever that function returns. In a sense you can think of it like... after the function is called... the call itself is "replaced" with the return value.

Example:

1
2
3
4
5
// a function to add 2 values together
int add(int a, int b)
{
    return a+b;
}


Then later if we do this:

1
2
3
4
    int foo = add(3,6);  // <- since 'add' will run and will return a value of 9... this means
        // the expression 'add(3,6)' gets evaluated to 9... which means it'd sort of be like
        // doing this:
    int foo = 9; // <- the call sort of gets "replaced" with the returned value 


Putting it in a cout statement is the same thing:
1
2
cout << add(13+12);  // <-  here it'd return 25 .... so it'd be like:
cout << 25;


And in fact.. you can put the function call anywhere you could put an int... because it is an int.

1
2
3
4
int foo = add( 1, add(6,  add(2, 3) ) );  // <- add(2,3) is 5
          add( 1, add(6,     5      ) );  // <- add(6,5) is 11
          add( 1,         11          );  // <- add(1,11) is 12
int foo = 12;




The return statement, in addition to the above, also 'ends' the function so no further code will execute in that function. So if you do this:

1
2
3
4
5
6
int func(int a)
{
    return a + 4; // <- function exits here

    cout << "This will never be executed";
}


With that in mind... main is kind of like a special case. Your program ends when main is done executing... and since doing a return in main causes it to exit, that's when your program ends.
Last edited on
Oh my God, I LOVE that explanation. Thanks so much! Are you a teacher?
No.... but sometimes I think I could have been. ;P
Topic archived. No new replies allowed.