Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is abs() and fabs() defined in two different headers in C

The standard library function abs() is declared in stdlib.h, while fabs() is in math.h.

Why are they reside in different headers?

like image 556
Sanjana Jose Avatar asked Aug 23 '16 09:08

Sanjana Jose


People also ask

What is the difference between abs () and fabs () functions in C?

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.

What is the difference between abs and fabs?

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.

Why do we use fabs in C programming?

In the C Programming Language, the fabs function returns the absolute value of a floating-point number.

Can we use abs for float in C?

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.


1 Answers

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:

  1. 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).
  2. Not many machines had floating point support. For example, you would need to buy an optional FPP for PDP-11 [2], there is also libfpsim simulation library in Unix to mitigate that, so floating point can be hardly used in early C programs.

1. A History of UNIX before Berkeley: UNIX Evolution: 1975-1984

2. PDP-11 architecture

like image 131
myaut Avatar answered Sep 17 '22 23:09

myaut