This post is for mastery points 11 and 12.

CC licensed photo by Mario Klingemann on Flickr
CC licensed photo by Mario Klingemann on Flickr

I created a video explaining how to create a function and then call it later in your code. Believe me it’s really easy.

First you should know that a function is a predefined piece of code contained like in a capsule. Each time ou need the code you call the function and use the code inside of it. You can write your own functions or use the functions that are contained in the different C++ libraries.  Another definitions for function could be: “a group of statements that is given a name, and which can be called from some point of the program”.

To create a function you need to write the type of data that its going to return, because functions have to return something. Then you have to name your function and say what its going to transform. That’s right, as you may have figured out, functions take something, perform a transformation and return something else. It’s like a little a machine.

Look at the following example:

// function example
#include <iostream>
using namespace std;

int addition (int a, int b) /*the first int means that this function is going to return an interger, the second and third int's mean that this function takes an int called "a" 
another int called "b".*/
  int r;
  return r;
/*in this part of the function you declare another variable, this is called a local variable because is used only in the function. The variable is going to store the value of the sum of "a" and "b". Then you need to say what is going to return the function, in this cases we return r becauce that is the value we want.*/
int main ()
  int z;
  z = addition (5,3);
  cout << "The result is " << z;


CC BY 4.0 Mastery11 & Mastery12 by Octavio Rojas is licensed under a Creative Commons Attribution 4.0 International License.