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() {
}
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
Writing your own function can be done with the following syntax:
void
: indicates that your function has no return valueint
: integer numberdouble
: floating-point numberbool
: Boolean (true/false)char
: letterstd::string
: wordstd::vector
: vectorvoid
) 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.main
function (or from inside another function)
#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
#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
#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
#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
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
.
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!
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.