Using functions

I've been trying to get my head around functions and came across this used as an example, i get everything up until it says return r - what does that do?

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

int addition (int a, int b)
{
  int r;
  r=a+b;
  return r;
}

int main ()
{
  int z;
  z = addition (5,3);
  cout << "The result is " << z;
}
Last edited on
Some functions (many of them) are used to generate some value. In this case, the function addition is being used to add two numbers together.

main calls addition, because main wants two numbers added together. The function addition then does some work, and adds two numbers together, and comes up with a value. The answer. a+b.

main wants to know that value. main needs to get that calculated value back from the function addition. We could say that the function addition needs to return that value.

Functions that return a value do so using the return keyword. return means "take this value here, and whoever called this function, they get that value in the place where they called this function".

In this simple example, you could read

z = addition (5,3);

as

z = whatever is returned from this function call: addition (5,3)
Topic archived. No new replies allowed.