Pure Function in C++



Pure functions always return the same result for the same argument values. They only return the result and there are no extra side effects like argument modification, I/O stream, output generation etc.

Following are the examples of pure vs impure functions:

  • Pure Function: sin(), strlen(), sqrt(), max(), pow(), floor() etc.
  • Impure Function: rand(), time(), etc.

There are many pure functions in C language such as strlen(), strcmp(), strchr(), strrchr(), strstr(), toupper(), tolower(), abs(), sin(), cos(), sqrt(), exp(), log(), pow(), fabs(), etc.

Here we are explaining a few pure functions with their usages and examples:

The strlen() Function

In C++, strlen() is used to find the length of the string. To see its demonstration we will assign input string to display both string with its length.

Example

In this example, we are printing the given string and its length.

#include<iostream>
#include<string.h>
using namespace std;

int main() {
   char str[] = "Rainbows are beautiful";
   int count = 0;

   cout << "The string is " << str << endl;
   cout << "The length of the string is " << strlen(str);

   return 0;
}

The above program produces the following output:

The string is Rainbows are beautiful
The length of the string is 22    

The sqrt() Function

The sqrt() function is used to find the square root of a number. For example: square root of 2 is 4, 3 is 9, 4 is 16, etc.

Example

In this example, we are finding square root of a number using sqrt() function.

#include <iostream>
#include <cmath>

using namespace std;
int main() {
   int num = 9;

   cout << "Square root of " << num << " is " << sqrt(num);

   return 0;
}

The above program produces the following output:

Square root of 9 is 3

The pow() Function

The pow() function is the mathematical function that belongs to the header cmath and used to find the power of a given number.

Below is the example of pow() function:

  • pow(3, 4): It is calculated as 3**4 which is equivalent to 3*3*3*3 (81).
  • pow(5, 2): It is calculated as 5**2 which is equivalent to 5*5 (25).

Example

In this example, we use the pow() function with two arguments: base and exponent. The function calculate the value of base raised to the power of exponent, and stores the result.

#include <iostream>
#include <cmath> 

using namespace std;

int main() {
   double base = 2.0;
   double exponent = 3.0;

   // base raised to the power exponent
   double result = pow(base, exponent);

   // show the result
   cout << base << " raised to the power " << exponent << " is " << result << endl;

   return 0;
}

The above code produces the following output:

2 raised to the power 3 is 8
Updated on: 2025-06-02T14:18:35+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements