The standard library function abs()
is declared in stdlib.h
, while fabs()
is in math.h
.
Why are they reside in different headers?
The difference is that math. fabs(number) will always return a floating-point number even if the argument is an integer, whereas abs() will return a floating-point or an integer depending upon the argument.
The abs() functions returns the absolute value as an integer or floating point value depending on what value was supplied dot it. But the fabs) function will always return the value as floating point irrespective of whether an integer or a floating point was supplied to it as a parameter.
In the C Programming Language, the fabs function returns the absolute value of a floating-point number.
abs is only implemented for integer in C. That's why the answers are all recommending you use fabs, which is the floating-point equivalent.
math.h first appears in 7th Research Unix. It is hard to tell how it got there. For example, [1] claims that bits of C library were merged from "PWB/Unix" which included troff
and C compiler pcc
, but I cannot prove it.
Another interesting piece of information is library manual from V7 Unix: intro.3:
(3) These functions, together with those of section 2 and those marked (3S), constitute library libc, which is automatically loaded by the C compiler cc(1) and the Fortran compiler f77(1). The link editor ld(1) searches this library under the `-lc' option. Declarations for some of these functions may be obtained from include files indicated on the appropri- ate pages.
<...>
(3M) These functions constitute the math library, libm. They are automati- cally loaded as needed by the Fortran compiler f77(1). The link editor searches this library under the `-lm' option. Declarations for these functions may be obtained from the include file <math.h>.
If you look into V7 commands makefiles, only few C programs are linked with -lm
flag. So my conclusion is speculative:
libm.a
(and math.h
) was primarily needed for FORTRAN programs mostly, so it was separated into library to reduce binary footprint (note that it was linked statically).1. A History of UNIX before Berkeley: UNIX Evolution: 1975-1984
2. PDP-11 architecture
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With