C++ cinttypes::abs() Function



The std::cinttypes::abs() function in C++, provides an efficient way to calculate the absolute value of the integer types. It ensures the compatibility with int, long and long long types,returning the non-negative equivalent of its input.

This function is used for handling the signed integers, as it converts the negative values to positive while leaving the positive values unchanged.

Syntax

Following is the syntax for std::cinttypes::abs() function.

int abs( int num );
or
long abs( long num );

Parameters

  • num − It indicates the integer value.

Return value

This function returns the absolute value of num, if it is representable.

Example 1

Let's look at the following example, where we are going to get the absolute value of the negative integer.

#include <cinttypes>
#include <iostream>
int main() {
   int64_t a = -1122;
   int64_t x = std::abs(a);
   std::cout << "Result : " << x << std::endl;
   return 0;
}

Output

Output of the above code is as follows −

Result : 1122

Example 2

Consider the following example, we are going to get the absolute value of the zero.

#include <cinttypes>
#include <iostream>
int main() {
   int32_t x = 0;
   int32_t a = std::abs(x);
   std::cout << "Result : " << a << std::endl;
   return 0;
}

Output

Following is the output of the above code −

Result : 0

Example 3

In the following example, we are going to get the difference using the absolute value.

#include <cinttypes>
#include <iostream>
int main() {
   int32_t x1 = 11, x2 = 1;
   int32_t a = std::abs(x1 - x2);
   std::cout << "Result : " << a << std::endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

Result : 10
cpp_cinttypes.htm
Advertisements