Function Declarations


A function is a computation that manipulates variables, and optionally changes the state of the program. It takes as input some variables and returns some single variable as output.

To declare a function we write the type of the variable it returns, the name of the function, and then in parenthesis a list of the variables it takes as input, separated by commas. The contents of the function are put inside curly brackets {}, and lists all of the statements the function executes, terminated by semicolons ;. A return statement is used to let the function finish and output a variable.

For example a function that takes two int variables called x and y and adds them together could look like this.

  1. int add_together(int x, int y) {
  2. int result = x + y;
  3. return result;
  4. }

We call functions by writing their name and putting the arguments to the function in parentheses, separated by commas. For example to call the above function and store the result in a variable added we would write the following.

  1. int added = add_together(10, 18);