C++ from the beginning, functions
Tags: cpp, tutorial, beginners
Published: 2021-11-08 18:37:11

---
title: C++ from the beginning, functions
published: true
series: C++ beginners
description: in this article, you learn what functions are and why use them and how you create your own functions
tags: cpp, tutorial, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/157ap4uzahictse2f2r0.jpg
---

> TLDR; functions are great cleaning up your code and create reusable code that you can use in many places

## The full series

- [Your first program](https://dev.to/azure/c-from-the-beginning-2o2l)
- [Variables](https://dev.to/azure/c-from-the-beginning-variables-22nm)
- [Working with input and output](https://dev.to/azure/c-from-the-beginning-input-and-output-5ad0)
- Functions, **you are here**
- Control flow
- Working with files
- Pointers
- Error management
- Structs and Classes

## Resources

- [CPP Snippets for VS Code](https://marketplace.visualstudio.com/items?itemName=chris-noring.cpp-snippets&ssr=false#overview)
- [C++ module](https://docs.microsoft.com/en-us/learn/modules/cpp-first-program?wt.mc_id=academic-0000-chnoring)v

## The "what" and "why" of functions

A function is a named reference containing a set of statements. The idea of a function is that you have set of statements that you see repeating in certain places in your code and you replace those with a function. Here's an example:

```cpp
int random_value = rand % 10 + 1;
statement;
statement;
random_value = rand % 5 + 1;
statement;
statement;
random_value = rand % 20 + 1;
```

In the code above, you generate a random value with different interval, 1-10, 1-5, 1-20. It makes sense to break this out to a function, like so:

```cpp
int getRandomValue(int range) 
{
  return rand % range + 1;
}
```

Then your code can be simplified like so:

```cpp
int random_value = getRandomValue(10);
statement;
statement;
random_value = getRandomValue(5);
statement;
statement;
random_value = getRandomValue(20);
```

An added bonus is your code is also more readable, `getRandomValue()` is easier to understand than `rand() % 20 + 1`

## Functions

Ok now that we understand what functions are for, let's take it slow and explain what makes out a function. A function needs a name, parenthesis and a return type. Additionally, it needs to start and end with curly braces, like so:

```cpp
<return type> <name>() {}
```

A more real example of the above would like so:

```cpp
int getRandomValue() 
{
  /* body */ 
}
```

There are few concepts you need to know about functions like:

- **header**, this is the part of the function where you declare its name, return type and parameters, values you want to pass into the function. Here's the header from the above code:

   ```cpp
   int getRandomValue()
   ```

- **body**, the body of the function is where things happen, what you want the function to do. The body content is defined within the curly braces:

   ```cpp
   return rand % range + 1;  
   ```
- **definition = body + header**, the header and body makes out what's called the function definition, like so:

   ```cpp
   int getRandomValue()
   {
     return rand % range + 1;
   }
   ```

   if you have sharp eyes, you might notice that `range` isn't defined, it's because it's a parameter and we haven't defined it yet.

- **parameters**, a parameter is a placeholder, a name and type capabable of storing what gets passed into a function. Here, `range` is the parameter:

   ```cpp
   int getRandomValue(int range)
   {
     return rand % range + 1; 
   }
   ```

- **invocation**, to call or _invocate_ a function, we need to call it by its name, and provide values to any parameters we might have defined. To call `getRandomValue` we need to add parenthesis and what's known as an argument (a value) to the `range` parameter:

   ```cpp
   getRandomValue(10)
   ```

   10 is the argument, the value, which is bound to the `range` parameter. You can declare many parameters to a function like so for example:

   ```cpp
   int add(int x, int y) 
   {
     return x + y; 
   }
   ```

   and call it like so: `add(2,2)`

## Return from a function

So far, you've seen how to declare function, add several parameters to it, but there's another important part of a function, what it returns. A function must have a return type, it's either `void` or a data type like so:

```cpp
void printSomething(string message) 
{
  cout << message;
}
```

if the the return type is something else than `void` then you need a `return` statement somewhere in the function body where you _return_ the value, like so:

```cpp
int add(int lhs, int rhs) 
{
  return lhs + rhs;
}
```

Without the `return` keyword, you would get a compilation error.

## Overloading, same functions defined many times with different params

When you defined a header, like so for example:

```cpp
int add(int a, int b) 
{

}
```

You have two parameters, what if you need three parameters or four, would I need to define a new function for each method? Fortunately, not, you can _overload_the function, meaning that you do define more functions, but they will all have the same name with the difference being that they have different number of parameters, like so:

```cpp
int add(int a, int b) 
{
  return add(a,b,0);
}

int add(int a, int b, int c) 
{
  return add(a,b,c, 0);
}

int add(int a, int b, int c, int d) 
{
  return a + b + c + d;
}
```

all this code enables us to use the version of `add()` we want, when we need it. Here's an example of using all four variants:

```cpp
int sum = add(2,3); // 5
sum = add(2,3,4); // 9
add(2,3,4,5) // 4
```

## Summary