Chapter 16 of 24

16. The C standard library

Use the tools C already provides

The C standard library is a collection of functions and types that a conforming C implementation provides. It offers common building blocks so you do not have to write every basic operation yourself.

  1. Identify the task, such as printing text, measuring a string, or allocating memory.
  2. Find the standard header that declares the needed function, then include it.
  3. Read the function's contract: what arguments it expects, what it returns, and how it reports failure.

Use a library function only when its input and result rules fit your situation. This chapter groups useful facilities by task and shows how to check their results.

The standard library provides portable functions and types. Learn these
headers as you need them:

Read each function's documentation for its valid inputs, return values, and
failure behavior. Check return values where failure is possible.

Learning the library by task

Do not try to memorize every library function. Start from the operation you
need, select the appropriate header, and check its documentation for:
parameter types, valid input ranges, return-value meaning, error reporting,
and ownership of any returned storage.

For example, <string.h> contains both string functions that expect a null
terminator and byte-oriented functions that use an explicit byte count. These
are not interchangeable: strlen needs a valid string, while memcpy
copies a specified number of bytes and requires non-overlapping regions.
qsort can sort arrays of many element types but requires a correctly written
comparison function and the right element size.

Functions in <ctype.h> accept EOF or values representable as
unsigned char. If a plain char may be negative, convert it before calling
a classification function:

#include <ctype.h>
#include <stdio.h>

int main(void)
{
    char character = ' ';
    if (isspace((unsigned char)character)) {
        puts("Whitespace");
    }
    return 0;
}

The standard library is portable, but system calls and compiler-specific
libraries are not necessarily so. When a function is not part of standard C,
identify the platform or library that provides it.

Checkpoint: Before using a library function, find its header, required
argument types, return-value rules, and whether it can fail.

Common library facilities in practice

The library's return value is often more reliable than assumptions about
global error state. Read the function documentation and inspect the result
first; use errno only when the function's specification says to.

qsort accepts a comparator callback. The comparator must return a negative
value when the first element sorts before the second, zero when they compare
equal, and a positive value when the first sorts after the second. Do not
subtract values to produce the result: subtraction can overflow.

int compare_ints(const void *left, const void *right)
{
    const int *a = left;
    const int *b = right;
    return (*a > *b) - (*a < *b);
}

Call it with the base pointer, element count, element size, and comparator:
qsort(values, length, sizeof values[0], compare_ints);. The function sorts
the array in place and does not promise a stable order for equal elements.

#include <inttypes.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    int32_t count = 9;
    double root = sqrt((double)count);
    printf("count=%" PRId32 ", square root=%.1f\n", count, root);
    return isfinite(root) ? 0 : 1;
}

PRId32 from <inttypes.h> supplies the correct format for int32_t.
Some toolchains require a separate math-library link option for sqrt.


Suggested topics

0% read