$: -> | xynapz |
open main menu
Part of series: c++

Functions and Basic Recursion in C++

/ 5 min read
Last Updated:

Functions are used to group related code in a single block of code, for the purpose of reusability and readibility of the code. Since all the code inside the main function is not humanly maintainable. To use a function, it first must exists somewhere in the program. If you need a function inside of a particular source file only, then it can be declared and defined there in the same file. If you need a function that has to be called in multiple file throught the project, or it might later be used in another project, then we generally put the declaration in a header file and the definition/implementation in a source file.

Declare a Function

The syntax for declaring a function is:

void process_myfile(std::string filename);

The above function declaration is composed up of return type void which means it returns nothing to the user, function identifier process_myfile is the actual function name, and it takes one input which is called arguments, which is of type std::string. A function can take multiple arguments as its input and can return one object(value or pointer or reference or void). In C/C++ both, a function can return void*(void pointer) which means it returns a pointer to an unspecified type, basically, it is a pointer type that can point to any data type in memory, and it cannot be dereferenced directly without casting to another type.

Define a Function

If we just declare a function without defining it in our code, then the link phase of the compilation process will fail because it is trying to call a non-existent code(empty function). So we need to define it somewhere, best in a seperate source file.

#include "my_func.h"

void process_myfile(std::string filename)
{
   std::cout << filename << std::endl;
}

Here, we are including the header file my_func.h so that the function declaration is visible to the definition and then we define the function, here it just prints the filename to the console.

Return values

A function can return a value as well, so that the user can use the value somewhere else in the other code.

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

It can used like shown below:

int sum = add(5,4);

Arguments VS Parameters

Parameters are the placeholder variable name while declaring a function, while the arguments are the actual input values passed to the function when calling.

Function Attributes

Current Function Name

For some reason, if you the name of the function, it can be accessed inside its definition by using func which is a predefined local variable provided by the compiler. Example:

int add(int a, int b)
{
    cout << "calling " << __func__ << endl;
    return a+b;
}

Function Overloading

Function overloading is a technique where we create multiple functions with the same name but with different parameters. These functions sharing the same name should have different number of paramerters or the parameter should be of different type. The return type doesn’t matters for function overloading in C++. Following are the syntax of function overloading.

int add(int a, int b);
double add(double a, double b);
int add(int a, int b, int c);nt add(int a, int b);
double add(double a, double b);
int add(int a, int b, int c);

All three functions are valid overloaded functions in C++, since they satisfy the criteria of either having different type parameters or different number of parameters are provided.

Recursion

Recursion is a programming technique in which a function calls iteself in order to perform an operation. A recursive function is composed up of a base case and a recursive case, base case is the condition in which the function doesn’t calls itself but return a value to terminate the recursion otherwise theres no stopping it. A recursive case is the call to the function itself by breaking the problem into a smaller problem. In the book “Data Structures and Algorithms Analysis in C++ by Mark Allen Weiss), the author explains recursion in a way that I will almost never forget and always take this same examle to explain to others as well. The example is a simple recursive function in basic high-school level algebra.

Lets take a function f(x) = 2.f(x - 1) + x2) that satisfies f(0) = 0 and is valid on positive numbers. So, from this we can get f(1) = 1, f(2)=6, f(3)=21 and f(4)=58. We get these values because we know that f(0)=0 if we didn’t know this was true, then our recursive function f(x) = 2.f(x - 1) + x2) is meaningless. So, lets write the code for this function.

int f(int x)
{
  if (x==0)
    return 0;
  else
    return 2 * f(x-1) + x * x;
}

Since we know that when the function gets the input argument 0, we know its value is 0 so we make that the case where the function terminates, i.e. the base case, and in the recursive case the in case of positive input arguments, the recurcive case will take us closer to the base case on each call of the function.

Recursion indeed is a tricky programming technique in the beginning but if you think of as just bringing the recusive case more closer to the base case on each call of the function and practice making that logic right over-time then recusion can be one of the most fun way of solving problems in CS. Thank you for your time till here.

References

  • Marc Gregoire – Professional C++, Fifth Edition (ISBN: 978-1-119-69540-0)
  • Mark Allen Weiss – Data Structures and Algorithms Analysis in C++, Fourth Edition (ISBN: 978-0-13-284737-7)
  • Geeksforgeeks.com – Difference between Argument and Parameter in C/C++ with Examples