Chapter 8: C Library Functions
Level 1 — Acquaintance
The standard library: what C provides out of the box and how Auto wraps it.
No C program works in isolation. The C standard library provides essential functions for I/O, string manipulation, mathematics, memory management, and system interaction. Auto wraps most of these in safer, more ergonomic interfaces while preserving the underlying C implementation.
8.1 General Properties
The C standard library is organized into headers, each declaring a set of related functions, types, and macros:
| Header | Purpose | Key functions |
|---|---|---|
<stdio.h> | Input/output | printf, scanf, fopen |
<stdlib.h> | General utilities | malloc, free, exit, abs |
<string.h> | String handling | strlen, strcmp, strcpy |
<math.h> | Mathematics | sqrt, sin, pow, ceil |
<time.h> | Date and time | time, clock, strftime |
<ctype.h> | Character classification | isdigit, toupper |
<assert.h> | Diagnostics | assert |
<errno.h> | Error indicators | errno, strerror |
<stddef.h> | Common definitions | size_t, NULL, offsetof |
To use a library function, you #include its header:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>Auto implicitly includes the transpiled equivalents. You do not write #include directly — the a2c transpiler adds the necessary headers based on which functions your code uses.
Error handling with errno: Many C library functions report errors by setting the global variable errno and returning a sentinel value (often NULL or -1).
// C: checking errno
errno = 0;
double result = sqrt(-1.0);
if (errno != 0) {
fprintf(stderr, "Error: %s\n", strerror(errno));
}Auto wraps these patterns into return types that force error checking (such as optional types ?T or result types Result<T, E>), eliminating the risk of forgetting to check errno.
Takeaway: In C, always check return values and
errnofor library calls. In Auto, the type system forces you to handle errors.
8.2 Integer Arithmetic
The <stdlib.h> header provides integer arithmetic utilities:
// C
int absolute = abs(-42); // 42
div_t result = div(17, 5); // result.quot = 3, result.rem = 2Auto provides these through built-in operators and library functions:
let quotient int = 17 / 5 // 3
let remainder int = 17 % 5 // 2
let absolute int = abs(-42) // 42