A function is a block of code which only runs when it is explicitly called.

In mathematics, a function is defined in the context of two sets usually called the domain and the range (or co-domain) and is a way of mapping each element of the domain to an uniquely specified element in the range.

The role of functions in programming langages is similar: you may think of a function as a black box that takes some input (possibly multiple inputs or even no input) and gives us some well-defined output (also possibly empty).

<aside> 📖 Example: a function called sum2 may be designed to take to numbers as input and return their sum as the output.

</aside>

Functions are important for reusing code: define the functionality once, and use it many times. Any changes/fixes also need be implemented only once.

Syntax:

<datatype of returned value> <function_name> ( <optional arguments> ) {

FUNCTION BLOCK

return <return value>;

}

Example:

#include <iostream>
using namespace std;

int es301(float y = 0.5){
	cout << y << endl;
	return y;
}

int main(){
	int x = es301(9.56);
	cout << x << endl;
}

<aside> ⚠️ Remember to declare the function before the first call, or you might get a compilation error.

</aside>

<aside> 📘 In due course, you might want to organize your commonly used functions in your own libraries, but we will come to this later.

</aside>

Function Arguments

On default arguments

On Scope — stack versus heap memory