Functions

Functions are blocks of statements defined under a name. They perform an operation and (often) return a result to the main program. The normal form is:

type funcname(param1, param2,...) {
	statements
}

type specifies the type of data that the function will return (e.g. int)

funcname is the identifier that will be used to call the function (e.g. test_end_game)

param1, param2, etc are a list of variables and data types. The variables receive the values when the function is called.

Functions can have no parameters, but they still need parentheses '()'.

An example:

int sum (int a, int b) {
	int c;
	c = a + b;
	return c;
}

To execute this function and save the result to a variable, we could use

int result = sum(10,12);

Passing arguments

There are two ways to pass arguments to a C++ function: by value and by reference.

Call by value copies the value of an argument into a parameter. Changes made to the parameter don't affect the argument. C++ uses call by value by default.

Call by reference works differently. In this method, the address of an argument is copied into the parameter. Changes made to the parameter affect the argument. We can use this method by passing a pointer to an argument instead of the actual argument. If we want an argument to be passed by reference, we can signify this in the function declaration using an & sign after the type (e.g. int&).