C Programming/stdlib.h/abs

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Many programming languages have functions that calculate absolute values of numbers, either having the name abs or Abs. In languages such as C, it has variants for long integers and floating point numbers called labs and fabs. All the functions take a signed number as a parameter, and returns the absolute value of that number in the same data type.

A very possible implementation of the abs functions, written in pseudo-code, would be:

function abs (number n) {
  if n >= 0 return n;
  else return -n;

C or C++[edit]

These functions are defined in the standard header math.h for C and cmath for C++:

int abs (int i);
long labs (long i);
double fabs (double i);
float fabsf (float i);
long double fabsl (long double i);