What are functions in C++?

This article will cover function declarations, function calls, function parameters, function scope, and function overloading.

We will cover function declarations, function calls, function parameters, function scope, and function overloading.

Purpose of functions

Functions help us developers to avoid repetition. Having a single area for application logic makes codebase navigation easier. Along with these benefits, breaking code into smaller functions leads us to write code in a modular way. This writing style helps us design software in a modular way. Modularity makes debugging easier and allows more direct debug statements. Instead of testing code as a whole, it helps us test single functions at a time, revealing bugs more easily.

What are  functions made out of?

A function has 4 parts: return type, name, parameters, and body. The return type ensures this function returns the given type. For example, if the return type is int, the function will return an integer. The name of the function is an identifier that the compiler can reference and use later. Parameters are defined between the parentheses. Every parameter tells us the order and type of the arguments that will be passed. The body or definition of the function is written in the function scope.

returnType FunctionName(type param1, type param2){
//body
}

Void Function

Functions that don't return anything will use the keyword void in place of a return type. We can say void is to mark functions that don't return anything.

void SayHello();

Difference between a function declaration and a function definition

A function declaration tells the compiler that a function exists with a given return type, name, and parameter list. This declaration is a promise made between the programmer and the compiler. A function declaration and its definition can be colocated.

Example function declaration

int sum(int a, int b);

Example function definition

int sum(int a,int b){
  return a+b;
}

Function call

Once a function is created, it's ready to call and use it! Let's assume the example and call sum(int a, int b) function. Following

int main(){
  // call sum with arguments a=2, b=3
  int val = sum(2,3);
  cout << val << "\n";
}

Overloading Functions

Overloading functions helps us achieve more complex function designs. Overloading functions means that multiple parameter setups are accepted for a single function name. Here is an example of declarations of that.

int sum(int a, int b);
int sum(int a, int b, int c);
double sum(double a, double b);

As previously, these are just the declarations functions still need definition as such so:

int sum(int a, int b){
  return a + b;
}
int sum(int a, int b, int c){
  return a + b + c;
}
double sum(double a, double b){ 
  return a + b;
}