Functions

What is a function?

A function is a block of code that carries out a specific task or action and can be reused later on.

Functions allow us to:

  • Write repeatable code - any number of statements can be wrapped into a function and used elsewhere in our program
  • Write readable code - all lines of code inserted into our function can be given a name that is easy to understand

Designing a Function

There are 3 main components to consider when writing a basic function in C++:

  1. A function name that accurately represents what the function is meant to do, and is easily digestible for anyone who reads your code
  2. A return value, aka what your function will be returning to the user after it is called. In C++ we either put a data type name (i.e. int) or void, which means nothing will be returned after this function finishes.
  3. Optional parameters that should be passed when the user calls this function. A parameter is just a bit of data that is given to the function for it to use when it starts going. You can have any number of parameters that you feel are necessary

Function Prototype

Now that we know the components of a function, we can look at the actual syntax for writing one

Here's an example of a simple function declaration

std::string capitalize_name(std::string name) { // Code here… }