Pure and Impure functions in C++

This tutorial is about pure and impure functions in C++. In C++, functions that follow below conditions are said to be pure.

  • They return the same value for the same argument passed.
  • They have no side effects such as I/O stream, modification in the argument, etc.

Functions that are not pure are called impure functions. We will see more about such functions in C++ in this tutorial with examples.

Pure function in C++: Examples

A pure function in C++ has the same return value for the same argument without any side effects.

For example, let’s consider- max() function. As we all know max() in C++ is used to find out the maximum of two values that are passed as arguments. Now for a fixed value of arguments, this function will always give the same output. Therefore, we can say max() is a pure function. Have a look at the code.

#include <iostream>

int main()
{
  int a = 34, b = 35;
  std::cout << "max(a, b) = " << std::max(a, b) << std::endl;
  
  std::cout << "max(34, 35) = " << std::max(34, 35) << std::endl;
  
  return 0;
}

Output:

max(a, b) = 35
max(34, 35) = 35

Some other examples of pure functions are floor(), strlen(), sqrt(), etc. All these functions follow the condition to be pure functions.

Impure function in C++: Examples

An impure function in C++ is a function that is not pure. If a function does not meet any of the above-specified conditions, then it is called an impure function. Let’s see an example.

Consider a function with the following definition.

void fun()
{
  static int x = 0;
  x++;
  return x;
}

Since there is no formal parameter for this function, for it to be pure function it should give same result after every call. But that doesn’t happen because static has been used. See the output below.

#include <iostream>

using namespace std;
int fun();

int fun()
{
  static int x = 0;
  x++;
  return x;
}

int main()
{
  int i;
  for(i=0;i<3;i++)
    cout << fun() << endl;
    
  return 0;
}

And the output…

1
2
3

Hence we can conclude after observing these outputs that function fun() is an impure function. In the same way, functions with these definitions would also be impure. Have a look at the following.

int fun(int *a)
{
  return *a;
}

And

void fun(int *a)
{
  ++*a;
}

These are examples of impure functions.

Thank you.

Also read: Virtual Function in C++

Leave a Reply

Your email address will not be published. Required fields are marked *