⇦ Back

Often when coding you will find yourself wanting to reuse the same block of code over-and-over. That’s where functions come into use: they allow you to call a block of code whenever you want.

Functions are sometimes also called methods, procedures or sub-routines.

Every C++ programme needs to have at least a main function:

// The most basic C++ programme consists of one function called main
int main() {
}

1 Built-In Functions

C++ comes with a lot of functions already built-in. For example, taking the square root of a number is a fairly common operation so it’s useful to remember that a function to do this is already included in C++’s standard library. It’s called sqrt() and it’s in the cmath header, so we need to remember to include that in our source code:

#include <iostream>
#include <cmath>

int main() {
    // Take the square root of a number
    std::cout << sqrt(16) << "\n";
}
4

Another example is generating a random number. This can be done with rand() % x where x is one more than the largest number you would want to see (ie rand() % 6 will generate a random number between 0 and 5):

#include <iostream>

int main() {
    // Simulate a dice roll
    int dice_roll = rand() % 6 + 1;
    std::cout << dice_roll << "\n";
}
2

2 Custom Functions

Writing your own function can be done with the following syntax:

  • The declaration of the function needs to have the following:
    • A data type for the return value of the function. Some possible return types include:
      • void: indicates that your function has no return value
      • int: integer number
      • double: floating-point number
      • bool: Boolean (true/false)
      • char: letter
      • std::string: word
      • std::vector: vector
    • A name for the function
    • The function’s parameters - if there are any - must be declared inside round brackets. If there are more than one they should be comma-separated.
  • The definition (or body of the function) will have:
    • Code statements, written inside a pair of curly brackets
    • If you have a return value (ie if your function’s type is not void) then it must be returned using the return statement on the last line of your function’s definition. If you return a value before the end of the function the code that follows the return statement will not run! The return statement causes a function to end.
  • Your new function can be called from inside the main function (or from inside another function)
    • Call your function by using its name and providing arguments (values for the parameters) inside round brackets if there are any. These arguments must be in the same order as the parameters were declared in the function declaration. If there are no parameters you still need to have the round brackets, but these will be empty.
    • If there is a return value, initialise a variable equal to the function and the return value will then be assigned to this variable

2.1 With No Parameters and No Return Value

#include <iostream>

void modulo() {
    std::cout << "The modulo is the remainder after a division" << "\n";
}

int main() {
    // Call a custom function
    modulo();
}
The modulo is the remainder after a division

2.2 With No Parameters but a Return Value

#include <iostream>
#include <string>

std::string modulo() {
    return "The modulo is the remainder after a division";
}

int main() {
    // Call a custom function
    std::string message = modulo();
    std::cout << message << "\n";
}
The modulo is the remainder after a division

2.3 With Parameters but No Return Value

#include <iostream>

// Calculate and print the remainder when one number is divided by another
void modulo(int dividend, int divisor) {
    int remainder = dividend % divisor;
    std::cout << "The remainder is " << remainder << "\n";
}

int main() {
    // Call a custom function
    modulo(11, 10);
}
The remainder is 1

2.4 With Parameters and also a Return Value

#include <iostream>

// Calculate and return the remainder when one number is divided by another
int modulo(int dividend, int divisor) {
    int remainder = dividend % divisor;
    return remainder;
}

int main() {
    // Call a custom function
    int answer = modulo(11, 10);
    std::cout << "The remainder is " << answer << "\n";
}
The remainder is 1

2.5 Default Parameters

Setting a parameter equal to a value in a function’s declaration will make that value its default value. This means you can now call the function without specifying a value for this argument (and it will assume you want to use the default value):

#include <iostream>

// Calculate and return the remainder when one number is divided by another
int modulo(int dividend, int divisor = 10) {
    int remainder = dividend % divisor;
    return remainder;
}

int main() {
    // Call a custom function
    int answer = modulo(11);
    std::cout << "The remainder is " << answer << "\n";
}
The remainder is 1

Notice that in the above example we just did the call with modulo(11); instead of modulo(11, 10); because the function definition had int divisor = 10 setting the default value of divisor.

2.6 Function Overloading

In C++ you can define multiple functions with the same name! This is possible as long as the functions have different types (or different numbers) of parameters:

#include <iostream>

void print_number(int num) {
    std::cout << "The number is " << num << "\n";
}

void print_number(std::string num) {
    std::cout << "The number is spelt '" << num << "'\n";
}

int main() {
    print_number(8);
    print_number("eight");
}
The number is 8
The number is spelt 'eight'

C++ automatically knows which function to use from what data type the argument is!

2.7 Function Templates

Up until now, each parameter in a function definition has had one and only one data type. If you want a parameter to be able to have one of a number of types, you can use a template to essentially create a generic data type:

#include <iostream>

template <typename T>
void print_number(T num) {
    // This will work with variables of int, string, double and Boolean data types
    std::cout << "The number is " << num << "\n";
}
int main() {
    print_number(8);
    print_number("eight");
    print_number(8.1);
    print_number(true);
}
The number is 8
The number is eight
The number is 8.1
The number is 1

This will only work if the code inside the function can use variables of any of those data types! Trying to pass in a vector, for example, wouldn’t work.

⇦ Back