Functions

Functions

Functions are pieces of code that get executed when a function is called. A simple function that prints out a message:

#include <iostream>
void myfunction(){
	std::cout << "Hello from a function." << std::endl;
}

int main(){
	myfunction(); // call to a function
}

Explanation: void is type, myfunction is function name, the function accepts no parameters hence the empty () parenthesis. { statements; } is the function body. A simplified function signature is:

type functionName( optional parameters){
	statements;
}

Function parameters

Function can accept parameters. Parameters are declared inside the parenthesis, for example (int x), (char c), (double d, bool b). Simple function parameter example:

#include <iostream>
void myfunction(int x){
	std::cout << "x is: " << x << std::endl;
}
int main(){
	myfunction(456);
}

Arguments can be passed by value and by reference &. Example:

#include <iostream>
void by value(int x){
	std::cout << "x is: " << x << std::endl;
}
void by reference(int& x){
	x++; // we can now modify the value of a parameter
	std::cout << "x is: " << x << std::endl;
}
int main(){
	int a = 123;
	by value(a); // Pass by value
	by reference(a); // Pass by reference, a is now 124
}

In simple terms - when passed by value, the function can not modify the value of a passed-in argument, when passed by reference (sometype& var) the function can modify the value of a passed-in argument.

Declaration and definition

There are function declaration and function definition. Function declaration declares the function name and type. Function definition connects the function declaration with its body. Example:

#include <iostream>
void myfunction(); // function declaration

int main(){
	myfunction(); // call to a function
}

void myfunction() { // function definition
	std::cout << "Hello from a function." << std::endl;
}

Return values

Functions can return values using the return statement. Return statement ends the function. Example:

#include <iostream>
int mysum(int x, int y){
	return x + y; // return statement
}

int main(){
	int z;
	z = mysum(10, 20);
	std::cout << "The result is: " << z;
}