# Programming in C (Fourth Edition) (2015)

### B. The Standard C Library

The standard C library contains a large selection of functions that might be called from a C program. This section does not list all of these functions, but rather most of the more commonly used ones. For a complete listing of all the functions that are available, consult the documentation that was included with your compiler, or check one of the resources listed in *Appendix E*, “*Resources*.”

Among the routines not described in this appendix are ones for manipulating the date and time (such as time, ctime, and localtime), performing nonlocal jumps (setjmp and longjmp), generating diagnostics (assert), handling a variable number of arguments (va_list,va_start, va_arg, and va_end), handling signals (signal and raise), dealing with localization (as defined in <locale.h>), and dealing with wide character strings.

**Standard Header Files**

This section describes the contents of some standard header files: <stddef.h>, <stdbool.h>, <limits.h>, <float.h>, and <stdinit.h>.

**<stddef.h>**

This header file contains some standard definitions, such as the following:

**<limits.h>**

This header file contains various implementation-defined limits for character and integer data types. Certain minimum values are guaranteed by the ANSI standard. These are noted at the end of each description inside parentheses.

**<stdbool.h>**

This header file contains definitions for working with Boolean variables (type _Bool).

**<float.h>**

This header file defines various limits associated with floating-point arithmetic. Minimum magnitudes are noted at the end of each description inside parentheses. Note that all of the definitions are not listed here.

Similar definitions exist for double and long double types. Just replace the leading FLT with DBL for doubles, and with LDBL for long doubles. For example, DBL_DIG gives the number of digits of precision for a double, and LDBL_DIG gives it for a long double.

You should also note that the header file <fenv.h> is used to get information and have more control over the floating-point environment. For example, there’s a function called fesetround that allows you to specify the direction of rounding to a value as defined in <fenv.h>:FE_TONEAREST, FE_UPWARD, FE_DOWNWARD, or FE_TOWARDZERO. You also have the ability to clear, raise, or test floating-point exceptions, using the feclearexcept, feraiseexcept, and fetextexcept functions, respectively.

**<stdint.h>**

This header file defines various type definitions and constants that you can use to work with integers in a more machine-independent fashion. For example, the typedef int32_t can be used to declare a signed integer variable of exactly 32 bits, without having to know the exact 32-bit integer data type on the system on which the program is being compiled. Similarly, int_least32_t can be used to declare an integer with a width of at least 32 bits. Other types of typedefs allow you to select the fastest integer representations, for example. For more information, you can take a look at the file on your system or consult your documentation.

A few other useful definitions from this header file are as follows:

**String Functions**

The following functions perform operations on character arrays. In the description of these routines, *s*, *s1*, and *s2* represent pointers to null-terminated character arrays, *c* is an int, and *n* represents an integer of type size_t (defined in stddef.h). For the strnxxx routines, *s1* and *s2*can point to character arrays that aren’t null-terminated.

To use any of these functions, you should include the header file <string.h> in your program:

#include <string.h>

char *strcat (*s1, s2*)

Concatenates the character string *s2* to the end of *s1*, placing a null character at the end of the final string. The function returns *s1*.

char *strchr (*s, c*)

Searches the string *s* for the first occurrence of the character *c*. If it is found, a pointer to the character is returned; otherwise, a null pointer is returned.

int strcmp (*s1, s2*)

Compares strings *s1* and *s2* and returns a value less than zero if *s1* is less than *s2*, equal to zero if *s1* is equal to *s2*, and greater than zero if *s1* is greater than *s2*.

char *strcoll (*s1, s2*)

Is like strcmp, except *s1* and *s2* are pointers to strings represented in the current locale.

char *strcpy (*s1, s2*)

Copies the string *s2* to *s1*, returning *s1*.

char *strerror (*n*)

Returns the error message associated with error number *n*.

size_t strcspn (*s1, s2*)

Counts the maximum number of initial characters in *s1* that consist of any characters but those in *s2*, returning the result.

size_t strlen (*s*)

Returns the number of characters in *s*, excluding the null character.

char *strncat (*s1, s2, n*)

Copies *s2* to the *end* of *s1* until either the null character is reached or *n* characters have been copied, whichever occurs first. Returns *s1*.

int strncmp (*s1, s2, n*)

Performs the same function as strcmp, except that at most *n* characters from the strings are compared.

char *strncpy (*s1, s2, n*)

Copies *s2* to *s1* until either the null character is reached or *n* characters have been copied, whichever occurs first. Returns *s1*.

char *strrchr (*s, c*)

Searches the string *s* for the last occurrence of the character *c*. If found, a pointer to the character in *s* is returned; otherwise, the null pointer is returned.

char *strpbrk (*s1, s2*)

Locates the first occurrence of any character from *s2* inside *s1*, returning a pointer to it or the null pointer if not found.

size_t strspn (*s1, s2*)

Counts the maximum number of initial characters in *s1* that consist only of characters from *s2*, returning the result.

char *strstr (*s1, s2*)

Searches the string *s1* for the first occurrence of the string *s2*. If found, a pointer to the start of where *s2* is located inside *s1* is returned; otherwise, if *s2* is not located inside *s1*, the null pointer is returned.

char *strtok (*s1, s2*)

Breaks the string *s1* into tokens based on delimiter characters in *s2*. For the first call, *s1* is the string being parsed and *s2* contains a list of characters that delimit the tokens. The function places a null character in *s1* to mark the end of each token as it is found and returns a pointer to the start of the token. On subsequent calls, *s1* should be a null pointer. When no more tokens remain, a null pointer is returned.

size_t strxfrm (*s1, s2, n*)

Transforms up to *n* characters from the string *s2*, placing the result in *s1*. Two such transformed strings from the current locale can then be compared with strcmp.

**Memory Functions**

The following routines deal with arrays of characters. They are designed for efficient searching of memory and for copying data from one area of memory to another. They require the header file **<string.h>**:

#include <string.h>

In the description of these routines, *m1* and *m2* are of type void *, *c* is an int that gets converted by the routine to an unsigned char, and *n* is an integer of type size_t.

void *memchr (*m1, c, n*)

Searches *m1* for the first occurrence of *c**,* returning a pointer to it if found, or the null pointer, if not found after examining *n* characters.

void *memcmp (*m1, m2, n*)

Compares the corresponding first *n* characters from *m1* and *m2*. Zero is returned if both arrays are identical in their first *n* characters. If they’re not, the difference between the corresponding characters from *m1* and *m2* that caused the first mismatch is returned. So, if the disagreeing character from *m1* was less than the corresponding character from *m2*, a value less than zero is returned; otherwise, a value greater than zero is returned.

void *memcpy (*m1, m2, n*)

Copies *n* characters from *m2* to *m1*, returning *m1*.

void *memmove (*m1, m2, n*)

Is like memcpy, but is guaranteed to work even if *m1* and *m2* overlap in memory.

void *memset (*m1, c, n*)

Sets the first *n* characters of *m1* to the value *c*. memset returns *m1*.

Note that these routines attach no special significance to null characters inside the arrays. They can be used with arrays other than character arrays provided you cast the pointers accordingly to void *. So, if data1 and data2 are each an array of 100 ints, the call

memcpy ((void *) data2, (void *) data1, sizeof (data1));

copies all 100 integers from data1 to data2.

**Character Functions**

The following functions deal with single characters. To use them, you must include the file <ctype.h> in your program:

#include <ctype.h>

Each of the functions that follow takes an int(*c*) as an argument and returns a TRUE value (nonzero), if the test is satisfied, and a FALSE (zero) value otherwise.

The following two functions are provided for performing character translation:

int tolower(*c*)

Returns the lowercase equivalent of *c*. If *c* is not an uppercase letter, *c* itself is returned.

int toupper(*c*)

Returns the uppercase equivalent of *c*. If *c* is not a lowercase letter, *c* itself is returned.

**I/O Functions**

The following describes some of the more commonly used I/O functions from the C library. You should include the header file <stdio.h> at the front of any program that uses one of these functions, using the following statement:

#include <stdio.h>

Included in this file are declarations for the I/O functions and definitions for the names EOF, NULL, stdin, stdout, stderr (all constant values), and FILE.

In the descriptions that follow, *fileName*, *fileName1*, *fileName2*, *accessMode*, and *format* are pointers to null-terminated strings, *buffer* is a pointer to a character array, *filePtr* is of type “pointer to FILE,” *n* and *size* are positive integer values of type size_t, and *i* and *c* are of type int.

void clearerr (*filePtr*)

Clears the end of file and error indicators associated with the file identified by *filePtr*.

int fclose (*filePtr*)

Closes the file identified by *filePtr* and returns zero if the close is successful, or returns EOF if an error occurs.

int feof (*filePtr*)

Returns nonzero if the identified file has reached the end of the file and returns zero otherwise.

int ferror (*filePtr*)

Checks for an error condition on the indicated file and returns zero if an error exists, and returns nonzero otherwise.

int fflush (*filePtr*)

Flushes (writes) any data from internal buffers to the indicated file, returning zero on success and the value EOF if an error occurs.

int fgetc (*filePtr*)

Returns the next character from the file identified by *filePtr*, or the value EOF if an end-of-file condition occurs. (Remember that this function returns an int.)

int fgetpos (*filePtr*, *fpos*)

Gets the current file position for the file associated with *filePtr*, storing it into the fpos_t (defined in <stdio.h>) variable pointed to by *fpos*. fgetpos returns zero on success, and returns nonzero on failure. See also the fsetpos function.

char *fgets (*buffer*, *i, filePtr*)

Reads characters from the indicated file, until either *i* − 1 characters are read or a newline character is read, whichever occurs first. Characters that are read are stored into the character array pointed to by *buffer*. If a newline character is read, it *will* be stored in the array. If an end of file is reached or an error occurs, the value NULL is returned; otherwise, *buffer* is returned.

FILE *fopen (*fileName, accessMode*)

Opens the specified file with the indicated access mode. Valid modes are "r" for reading, "w" for writing, "a" for appending to the end of an existing file, "r+" for read/write access starting at the beginning of an existing file, "w+" for read/write access (and the previous contents of the file, if it exists, are lost), and "a+" for read/write access with all writes going to the end of the file. If the file to be opened does not exist, it is created if the *accessMode* is write ("w", "w+") or append ("a", "a+"). If a file is opened in append mode ("a" or "a+"), it is not possible to overwrite existing data in the file.

On systems that distinguish binary from text files, the letter b must be appended to the access mode (as in "rb") to open a binary file.

If the fopen call is successful, a FILE pointer is returned to be used to identify the file in subsequent I/O operations; otherwise, a null pointer is returned.

int fprintf (*filePtr, format, arg1, arg2, ..., argn*)

Writes the specified arguments to the file identified by *filePtr*, according to the format specified by the character string *format*. Format characters are the same as for the printf function (see *Chapter 15*, “*Input and Output Operations in C*”). The number of characters written is returned. A negative return value indicates that an error occurred on output.

int fputc (*c, filePtr*)

Writes the value of *c* (converted to an unsigned char) to the file identified by *filePtr*, returning *c* if the write is successful, and the value EOF otherwise.

int fputs (*buffer, filePtr*)

Writes the characters in the array pointed to by *buffer* to the indicated file until the terminating null character in *buffer* is reached. A newline character is *not* automatically written to the file by this function. On failure, the value EOF is returned.

size_t fread (*buffer, size, n, filePtr*)

Reads *n* items of data from the identified file into *buffer*. Each item of data is *size* bytes in length. For example, the call

numread = fread (text, sizeof (char), 80, in_file);

reads 80 characters from the file identified by in_file and stores them into the array pointed to by text. The function returns the number of data items successfully read.

FILE *freopen (*fileName, accessMode, filePtr*)

Closes the file associated with *filePtr* and opens the file *fileName* with the specified *accessMode* (see the fopen function). The file that is opened is subsequently associated with *filePtr*. If the freopen call is successful, *filePtr* is returned; otherwise, a null pointer is returned. The freopen function is frequently used to reassign stdin, stdout, or stderr in the program. For example, the call

if ( freopen ("inputData", "r", stdin) == NULL ) {

...

}

has the effect of reassigning stdin to the file inputData, which is opened in read access mode. Subsequent I/O operations performed with stdin are performed with the file inputData, as if stdin had been redirected to this file when the program was executed.

int fscanf (*filePtr, format, arg1, arg2, ..., argn*)

Reads data items from the file identified by *filePtr*, according to the format specified by the character string *format*. The values that are read are stored in the arguments specified after *format*, each of which must be a pointer. The *format* characters that are allowed in format are the same as those for the scanf function (see *Chapter 15*). The fscanf function returns the number of items successfully read and assigned (excluding any %n assignments) or the value EOF if the end of file is reached before the first item is converted.

int fseek (*filePtr, offset, mode*)

Positions the indicated file to a point that is offset (a long int) bytes from the beginning of the file, from the current position in the file, or from the end of the file, depending upon the value of *mode* (an integer). If *mode* equals SEEK_SET, positioning is relative to the beginning of the file. If *mode* equals SEEK_CUR, positioning is relative to the current position in the file. If *mode* equals SEEK_END, positioning is relative to the end of the file. SEEK_SET, SEEK_CUR, and SEEK_END are defined in <stdio.h>.

On systems that distinguish between text and binary files, SEEK_END might not be supported for binary files. For text files, either *offset* must be zero or must be a value returned from a prior call to ftell. In the latter case, *mode* must be SEEK_SET.

If the fseek call is unsuccessful, a nonzero value is returned.

int fsetpos (*filePtr, fpos*)

Sets the current file position for the file associated with *filePtr* to the value pointed to by *fpos*, which is of type fpos_t (defined in <stdio.h>). Returns zero on success, and nonzero on failure. See also fgetpos.

long ftell (*filePtr*)

Returns the relative offset in bytes of the current position in the file identified by *filePtr*, or −1L on error.

size_t fwrite (*buffer, size, n, filePtr*)

Writes *n* items of data from *buffer* to the specified file. Each item of data is *size* bytes in length. Returns the number of items successfully written.

int getc (*filePtr*)

Reads and returns the next character from the indicated file. The value EOF is returned if an error occurs or if the end of the file is reached.

int getchar (void)

Reads and returns the next character from stdin. The value EOF is returned upon error or end of file.

char *gets (*buffer*)

Reads characters from stdin into *buffer* until a newline character is read. The newline character is *not* stored in *buffer*, and the character string is terminated with a null character. If an error occurs in performing the read, or if no characters are read, a null pointer is returned; otherwise, *buffer* is returned. This function has been removed from the ANSI C11 specification, but you may see this function in older code, so it is good to know what the function does.

void perror (*message*)

Writes an explanation of the last error to stderr, preceded by the string pointed to by *message*. For example, the code

#include <stdlib.h>

#include <stdio.h>

if ( (in = fopen ("data", "r")) == NULL ) {

perror ("data file read");

exit (EXIT_FAILURE);

}

produces an error message if the fopen call fails, possibly giving more details to the user about the reason for the failure.

int printf (*format, arg1, arg2, ..., argn*)

Writes the specified arguments to stdout, according to the format specified by the character string *format* (see *Chapter 15*). Returns the number of characters written.

int putc (*c, filePtr*)

Writes the value of *c* as an unsigned char to the indicated file. On success, *c* is returned; otherwise EOF is returned.

int putchar(*c*)

Writes the value of *c* as an unsigned char to stdout, returning *c* on success and EOF on failure.

int puts (*buffer*)

Writes the characters contained in buffer to stdout until a null character is encountered. A newline character is automatically written as the last character (unlike the fputs function). On error, EOF is returned.

int remove (*fileName*)

Removes the specified file. A nonzero value is returned on failure.

int rename (*fileName1, fileName2*)

Renames the file *fileName1* to *fileName2*, returning a nonzero result on failure.

void rewind (*filePtr*)

Resets the indicated file back to the beginning.

int scanf (*format, arg1, arg2, ..., argn*)

Reads items from stdin according to the format specified by the string *format* (see *Chapter 15*). The arguments that follow *format* must all be pointers. The number of items successfully read and assigned (excluding %n assignments) is returned by the function. The value EOF is returned if an end of file is encountered before any items have been converted.

FILE *tmpfile (void)

Creates and opens a temporary binary file in write update mode ("r+b"); it returns NULL if an error occurs. The temporary file is automatically removed when the program terminates. (A function called tmpnam is also available for creating unique, temporary file names.)

int ungetc (*c, filePtr*)

Effectively “puts back” a character to the indicated file. The character is not actually written to the file but is placed in a buffer associated with the file. The next call to getc returns this character. The ungetc function can only be called to “put back” one character to a file at a time; that is, a read operation must be performed on the file before another call to ungetc can be made. The function returns *c* if the character is successfully “put back”; otherwise, it returns the value EOF.

**In-Memory Format Conversion Functions**

The functions sprintf() and sscanf() are provided for performing data conversion in memory. These functions are analogous to the fprintf() and fscanf() functions, except a character string replaces the FILE pointer as the first argument. You should include the header file<stdio.h> in your program when using these routines.

int sprintf (*buffer, format, arg1, arg2, ..., argn*)

The specified arguments are converted according to the format specified by the character string *format* (see *Chapter 15*) and are placed into the character array pointed to by *buffer*. A null character is automatically placed at the end of the string inside *buffer*. The number of characters placed into *buffer* is returned, excluding the terminating null. As an example, the code

int version = 2;

char fname[125];

...

sprintf (fname, "/usr/data%i/2015", version);

results in the character string "/usr/data2/2005" being stored in fname.

int sscanf (*buffer, format, arg1, arg2, ..., argn*)

The values as specified by the character string *format* are read from *buffer* and stored in the corresponding pointer arguments that follow *format* (see *Chapter 15*). The number of items successfully converted is returned by this function. As an example, the code

char buffer[] = "July 16, 2014", month[10];

int day, year;

...

sscanf (buffer, "%s %d, %d", month, &day, &year);

stores the string "July" inside month, the integer value 16 inside day, and the integer value 2014 inside year. The code

#include <stdio.h>

#include <stdlib.h>

if ( sscanf (argv[1], "%f", &fval) != 1 ) {

fprintf (stderr, "Bad number: %s\n", argv[1]);

exit (EXIT_FAILURE);

}

converts the first command-line argument (pointed to by argv[1]) to a floating-point number, and checks the value returned by sscanf to see if a number was successfully read from argv[1]. (See the routines described in the next section for other ways to convert strings to numbers.)

**String-to-Number Conversion**

The following routines convert character strings to numbers. To use any of the routines described here, include the header file <stdlib.h> in your program:

#include <stdlib.h>

In the descriptions that follow, *s* is a pointer to a null-terminated string, *end* is a pointer to a character pointer, and *base* is an int.

All routines skip leading whitespace characters in the string and stop their scan upon encountering a character that is invalid for the type of value being converted.

double atof (*s*)

Converts the string pointed to by *s* into a floating-point number, returning the result.

int atoi (*s*)

Converts the string pointed to by *s* into an int, returning the result.

int atol (*s*)

Converts the string pointed to by *s* into a long int, returning the result.

int atoll (*s*)

Converts the string pointed to by *s* into a long long int, returning the result.

double strtod (*s, end*)

Converts *s* to double, returning the result. A pointer to the character that terminated the scan is stored inside the character pointer pointed to by *end*, provided *end* is not a null pointer.

As an example, the code

#include <stdlib.h>

...

char buffer[] = " 123.456xyz", *end;

double value;

...

value = strtod (buffer, &end);

has the effect of storing the value 123.456 inside value. The character pointer variable end is set by strtod to point to the character in buffer that terminated the scan. In this case, it is set pointing to the character 'x'.

float strtof (*s, end*)

Is like strtod, except converts its argument to float.

long int strtol (*s, end, base*)

Converts *s* to long int, returning the result. *base* is an integer base number between 2 and 36, inclusive. The integer is interpreted according to the specified base. If *base* is 0, the integer can be expressed in either base 10, octal (leading 0), or hexadecimal (leading 0x or 0X). If *base* is 16, the value can optionally be preceded by a leading 0x or 0X.

A pointer to the character that terminated the scan is stored inside the character pointer pointed to by *end*, provided *end* is not a null pointer.

long double strtold (*s*, *end*)

Is like strtod, except converts its argument to long double.

long long int strtoll (*s, end, base*)

Is like strtol, except a long long int is returned.

unsigned long int strtoul (*s, end, base*)

Converts *s* to unsigned long int, returning the result. The remaining arguments are interpreted as for strtol.

unsigned long long int strtoull (*s, end, base*)

Converts *s* to unsigned long long int, returning the result. The remaining arguments are interpreted as for strtol.

**Dynamic Memory Allocation Functions**

The following functions are available for allocating and freeing memory dynamically. For each of these functions, *n* and *size* represent integers of type size_t, and *pointer* represents a void pointer. To use these functions, include the following line in your program:

#include <stdlib.h>

void *calloc (*n, size*)

Allocates contiguous space for *n* items of data, where each item is *size* bytes in length. The allocated space is initially set to all zeroes. On success, a pointer to the allocated space is returned; on failure, the null pointer is returned.

void free (*pointer*)

Returns a block of memory pointed to by *pointer* that was previously allocated by a calloc(), malloc(), or realloc() call.

void *malloc (*size*)

Allocates contiguous space of *size* bytes, returning a pointer to the beginning of the allocated block if successful, and the null pointer otherwise.

void *realloc (*pointer, size*)

Changes the size of a previously allocated block to *size* bytes, returning a pointer to the new block (which might have moved), or a null pointer if an error occurs.

**Math Functions**

The following list identifies the math functions. To use these routines, include the following statement in your program:

#include <math.h>

The standard header file <tgmath.h> defines type-generic macros that can be used to call a function from the math or complex math libraries without worrying about the argument type. For example, you can use six different square root functions based upon the argument type and return type:

double sqrt (double x)

float sqrtf (float x)

long double sqrtl (long double x)

double complex csqrt (double complex x)

float complex csqrtf (float complex f)

long double complex csqrtl (long double complex)

Instead of having to worry about all six functions, you can include <tgmath.h> instead of <math.h> and <complex.h> and just use the “generic” version of the function under the name sqrt. The corresponding macro defined in <tgmath.h> ensures that the correct function gets called.

Returning to <math.h>, the following macros can be used to test specific properties of floating-point values given as argument(s):

int fpclassify (x)

Classifies *x* as NaN (FP_NAN), infinite (FP_INFINITE), normal (FP_NORMAL), subnormal (FP_SUBNORMAL), zero (FP_ZERO), or in some other implementation-defined category; each FP_... value is defined in math.h.

int isfin (x)

Does *x* represent a finite value?

int isinf (x)

Does *x* represent an infinite value?

int isgreater (x, y)

Is *x* > *y*?

int isgreaterequal (x, y)

Is *x* ≥ *y*?

int islessequal (x, y)

Is *x* ≤ *y*?

int islessgreater (x, y)

Is *x* < *y* or is *x* > *y*?

int isnan (x)

Is *x* a NaN (that is, not a number)?

int isnormal (x)

Is *x* a normal value?

int isunordered (x, y)

Are *x* and *y* unordered (for example, one or both might be NaNs)?

int signbit (x)

Is the sign of *x* negative?

In the list of functions that follows, *x*, *y*, and *z* are of type double, *r* is an angle expressed in radians and is of type double, and *n* is an int.

For more information about how errors are reported by these functions, consult your documentation.

double acos (*x*)^{1}

*1*. *The math library contains* *float**,* *double**, and* *long double* *versions of the math functions that take and return* *float**,* *double**, and* *long double* *values. The* *double* *versions are summarized here. The* *float* *versions have the same name with an* *f* *on the end (e.g.* *acosf**). The* *long double* *versions have an* *l* *on the end instead (e.g.* *acosl**).*

Returns the arccosine of *x**,* as an angle expressed in radians in the range [0, π]. *x* is in the range [−1, 1].

double acosh (*x*)

Returns the hyperbolic arccosine of *x**,* x *≥ 1*.

double asin (*x*)

Returns the arcsine of *x* as an angle expressed in radians in the range [−π/2, π/2]. *x* is in the range [−1, 1].

double asinh (*x*)

Returns the hyperbolic arcsine of *x*.

double atan (*x*)

Returns the arctangent of *x* as an angle expressed in radians in the range [−π/2, π/2].

double atanh (*x*)

Returns the hyperbolic arctangent of *x*, *|x| ≤ 1*.

double atan2 (*y, x*)

Returns the arctangent of *y/x* as an angle expressed in radians in the range [−π, π].

double ceil (*x*)

Returns the smallest integer value greater than or equal to *x*. Note that the value is returned as a double.

double copysign (*x, y*)

Returns a value whose magnitude is that of *x* and whose sign is that of *y*.

double cos (*r*)

Returns the cosine of *r*.

double cosh (*x*)

Returns the hyperbolic cosine of *x*.

double erf (*x*)

Computes and returns the error function of *x*.

double erfc (*x*)

Computes and returns the complementary error function of *x*.

double exp (*x*)

Returns e^{x}.

double expm1 (*x*)

Returns e^{x} − 1.

double fabs (*x*)

Returns the absolute value of *x*.

double fdim (*x, y*)

Returns *x* − *y* if *x* > *y*; otherwise, it returns 0.

double floor (*x*)

Returns the largest integer value less than or equal to *x*. Note that the value is returned as a double.

double fma (*x, y, z*)

Returns (*x* × *y*) + *z*.

double fmax (*x, y*)

Returns the maximum of *x* and *y*.

double fmin (*x, y*)

Returns the minimum of *x* and *y*.

double fmod (*x, y*)

Returns the floating-point remainder of dividing *x* by *y*. The sign of the result is that of *x*.

double frexp (*x, exp*)

Divides *x* into a normalized fraction and a power of two. Returns the fraction in the range [1/2, 1] and stores the exponent in the integer pointed to by *exp*. If *x* is zero, both the value returned and the exponent stored are zero.

int hypot (*x, y*)

Returns the square root of the sum of *x*^{2} + *y*^{2}.

int ilogb (*x*)

Extracts the exponent of *x* as a signed integer.

double ldexp (*x, n*)

Returns *x* × 2^{n}.

double lgamma (x)

Returns the natural logarithm of the absolute value of the gamma of *x*.

double log (x)

Returns the natural logarithm of *x*, *x* ≥ 0.

double logb (x)

Returns the signed exponent of *x*.

double log1p (*x*)

Returns the natural logarithm of (*x* + 1), *x* ≥ −1.

double log2 (x)

Returns log2 *x*, *x* ≥ 0.

double log10 (x)

Returns log10 x, x ≥ 0.

long int lrint (*x*)

Returns *x* rounded to the nearest long integer.

long long int llrint (*x*)

Returns *x* rounded to the nearest long long integer.

long long int llround (*x*)

Returns the value of *x* rounded to the nearest long long int. Halfway values are always rounded away from zero (so 0.5 always rounds to 1).

long int lround (*x*)

Returns the value of *x* rounded to the nearest long int. Halfway values are always rounded away from zero (so 0.5 always rounds to 1).

double modf (*x, ipart*)

Extracts the fractional and integral parts of *x*. The fractional part is returned and the integral part is stored in the double pointed to by *ipart*.

double nan (*s*)

Returns a NaN, if possible, according to the content specified by the string pointed to by *s*.

double nearbyint (*x*)

Returns the nearest integer to *x* in floating-point format.

double nextafter (*x, y*)

Returns the next representable value of *x* in the direction of *y*.

double nexttoward (*x, ly*)

Returns the next representable value of *x* in the direction of *y*. Similar to nextafter, except in this case the second argument is of type long double.

double pow (*x, y*)

Returns *x** ^{y}*. If

*x*is less than zero,

*y*must be an integer. If

*x*is equal to zero,

*y*must be greater than zero.

double remainder (*x, y*)

Returns the remainder of *x* divided by *y*.

double remquo (*x, y, quo*)

Returns the remainder of *x* divided by *y*, storing the quotient into the integer pointed to by *quo*.

double rint (*x*)

Returns the nearest integer to *x* in floating-point format. Might raise a floating-point exception if the value of the result is not equal to the argument *x*.

double round (*x*)

Returns the value of *x* rounded to the nearest integer in floating-point format. Halfway values are always rounded away from zero (so 0.5 always rounds to 1.0).

double scalbln (*x, n*)

Returns *x* × FLT_RADIX^{n}, where *n* is a long int.

double scalbn (*x, n*)

Returns *x* × FLT_RADIX^{n}.

double sin (*r*)

Returns the sine of *r*.

double sinh (*x*)

Returns the hyperbolic sine of *x*.

double sqrt (*x*)

Returns the square root of *x*, *x* ≥ 0.

double tan (*r*)

Returns the tangent of *r*.

double tanh (*x*)

Returns the hyperbolic tangent of *x*.

double tgamma (x)

Returns the gamma of *x*.

double trunc (*x*)

Truncates the argument *x* to an integer value, returning the result as a double.

**Complex Arithmetic**

This header file <complex.h> defines various type definitions and functions for working with complex numbers. Listed next are several macros that are defined in this file, followed by functions for performing complex arithmetic.

In the list of functions that follows, *y* and *z* are of type double complex, *x* is of type double, and *n* is an int.

double complex cabs (*z*)^{2}

*2*. *The complex math library contains* *float complex**,* *double complex**, and* *long double complex* *versions of the functions that take and return* *float complex**,* *double complex**, and* *long double complex* *values. The* *double complex* *versions are summarized here. The* *float complex* *versions have the same name with an* *f* *on the end (e.g.* *cacosf**). The* *long double* *versions have an* *l* *on the end instead (e.g.* *cacosl**).*

Returns the complex absolute value of *z*.

double complex cacos (*z*)

Returns the complex arc cosine of *z*.

double complex cacosh (*z*)

Returns the complex arc hyperbolic cosine of *z*.

double carg (*z*)

Returns the phase angle of *z*.

double complex casin (*z*)

Returns the complex arc sine of *z*.

double complex casinh (*z*)

Returns the complex arc hyperbolic sine of *z*.

double complex catan (*z*)

Returns the complex arc tangent of *z*.

double complex catanh (*z*)

Returns the complex arc hyperbolic tangent of *z*.

double complex ccos (*z*)

Returns the complex cosine of *z*.

double complex ccosh (*z*)

Returns the complex hyperbolic cosine of *z*.

double complex cexp (*z*)

Returns the complex natural exponential of *z*.

double cimag (*z*)

Returns the imaginary part of *z*.

double complex clog (*z*)

Returns the complex natural logarithm of *z*.

double complex conj (*z*)

Returns the complex conjugate of *z* (inverts the sign of its imaginary part).

double complex cpow (*y*, *z*)

Returns the complex power function *y*^{z}.

double complex cproj (*z*)

Returns the projection of *z* onto the Riemann sphere.

double complex creal (*z*)

Returns the real part of *z*.

double complex csin (*z*)

Returns the complex sine of *z*.

double complex csinh (*z*)

Returns the complex hyperbolic sine of *z*.

double complex csqrt (*z*)

Returns the complex square root of *z*.

double complex ctan (*z*)

Returns the complex tangent of *z*.

double complex ctanh (*z*)

Returns the complex hyperbolic tangent of *z*.

**General Utility Functions**

Some routines from the library don’t fit neatly into any of the previous categories. To use these routines, include the header file <stdlib.h>.

int abs (*n*)

Returns the absolute value of its int argument *n*.

void exit (*n*)

Terminates program execution, closing any open files and returning the exit status specified by its int argument *n*. EXIT_SUCCESS and EXIT_FAILURE, defined in <stdlib.h>, can be used to return a success or failure exit status, respectively.

Other related routines in the library that you might want to refer to are abort and atexit.

char *getenv (*s*)

Returns a pointer to the value of the environment variable pointed to by *s*, or a null pointer if the variable doesn’t exist. This function operates in a system-dependent way.

As an example, under Unix, the code

char *homedir;

...

homedir = getenv ("HOME");

could be used to get the value of the user’s HOME variable, storing a pointer to it inside homedir.

long int labs (*l*)

Returns the absolute value of its long int argument *l*.

long long int llabs (*ll*)

Returns the absolute value of its long long int argument *ll*.

void qsort (*arr, n, size, comp_fn*)

Sorts the data array pointed to by the void pointer *arr*. There are *n* elements in the array, each *size* bytes in length. *n* and *size* are of type size_t. The fourth argument is of type “pointer to function that returns int and that takes two void pointers as arguments.” qsort calls this function whenever it needs to compare two elements in the array, passing it pointers to the elements to compare. The function, which is user-supplied, is expected to compare the two elements and return a value less than zero, equal to zero, or greater than zero if the first element is less than, equal to, or greater than the second element, respectively.

Here is an example of how to use qsort to sort an array of 1,000 integers called data:

#include <stdlib.h>

...

int main (void)

{

int data[1000], comp_ints (void *, void *);

...

qsort (data, 1000, sizeof(int), comp_ints);

...

}

int comp_ints (void *p1, void *p2)

{

int i1 = * (int *) p1;

int i2 = * (int *) p2;

return i1 - i2;

}

Another routine called bsearch, which is not described here, takes similar arguments to qsort and performs a binary search of an ordered array of data.

int rand (void)

Returns a random number in the range [0, RAND_MAX], where RAND_MAX is defined in <stdlib.h> and has a minimum value of 32767. See also srand.

void srand (*seed*)

Seeds the random number generator to the unsigned int value *seed*.

int system (*s*)

Gives the command contained in the character array pointed to by *s* to the system for execution, returning a system-defined value. If *s* is the null pointer, system returns a nonzero value if a command processor is available to execute your commands.

As an example, under Unix, the call

system ("mkdir /usr/tmp/data");

causes the system to create a directory called /usr/tmp/data (assuming you have the proper permissions to do so).