C: The Standard Library
The standard library is like a toolbox — you don't need to forge your own hammer and screwdriver, just pick them up and use them. Understanding what each tool does helps you choose the right one.
1. math.h Mathematical Operations
Using math functions requires including the header and linking the math library:
// Preprocessor directive
#include <math.h>
Compile with the -lm flag: gcc program.c -lm.
(1) Common Math Functions
| Function | Purpose | Example |
|---|---|---|
fabs(x) |
Absolute value | fabs(-3.5) → 3.5 |
sqrt(x) |
Square root | sqrt(16.0) → 4.0 |
pow(x, y) |
x raised to the power y | pow(2.0, 10.0) → 1024.0 |
ceil(x) |
Round up | ceil(3.2) → 4.0 |
floor(x) |
Round down | floor(3.8) → 3.0 |
round(x) |
Round to nearest | round(3.5) → 4.0 |
fmod(x, y) |
Floating-point remainder | fmod(7.5, 2.5) → 0.0 |
log(x) |
Natural logarithm | log(2.718) → 1.0 |
log10(x) |
Common logarithm | log10(100.0) → 2.0 |
sin(x) |
Sine | sin(3.14/2) → 1.0 |
cos(x) |
Cosine | cos(0.0) → 1.0 |
tan(x) |
Tangent | tan(0.0) → 0.0 |
rad = deg * 3.14159265 / 180.0.
▶ Example
Calculate the distance between two points:
▶ Try it YourselfDistance: 5.00
2. stdlib.h General Utilities
(1) Random Numbers
// Function definition
int rand(void);
// Function definition
void srand(unsigned int seed);
rand() returns a pseudo-random integer between 0 and RAND_MAX. Without calling srand, every run of the program produces the same sequence of random numbers.
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>
// Preprocessor directive
#include <time.h>
// Function definition
int main(void) {
srand((unsigned int)time(NULL));
// For loop
for (int i = 0; i < 5; i++) {
// I/O operation
printf("%d ", rand());
}
// I/O operation
printf("\n");
// For loop
for (int i = 0; i < 5; i++) {
// I/O operation
printf("%d ", rand() % 100);
}
// I/O operation
printf("\n");
// Return result
return 0;
}
1804289383 846930886 1681692777 1714636915 1957747793
83 86 77 15 93
rand() % N doesn't provide good randomness in most implementations — lower bits may follow a pattern. For scenarios requiring high-quality randomness, use a more advanced random number generator.
(2) Type Conversion
| Function | Purpose |
|---|---|
atoi(str) |
String to int |
atol(str) |
String to long |
atof(str) |
String to double |
strtol(str, &end, base) |
String to long (with base) |
strtod(str, &end) |
String to double (with error detection) |
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>
// Function definition
int main(void) {
// Variable declaration
int a = atoi("42");
// Variable declaration
double b = atof("3.14");
// Variable declaration
long c = strtol("0xFF", NULL, 16);
// I/O operation
printf("a = %d\n", a);
// I/O operation
printf("b = %.2f\n", b);
// I/O operation
printf("c = %ld\n", c);
// Variable declaration
char *end;
// Variable declaration
long d = strtol("123abc", &end, 10);
// I/O operation
printf("d = %ld, Unconverted part: %s\n", d, end);
// Return result
return 0;
}
a = 42
b = 3.14
c = 255
d = 123, Unconverted part: abc
atoi cannot detect errors — invalid input returns 0, which is indistinguishable from a legitimate 0. Prefer strtol/strtod, which let you determine whether conversion succeeded via the end pointer.
(3) Dynamic Memory Management
// Function definition
void *malloc(size_t size);
// Function definition
void *calloc(size_t count, size_t size);
// Function definition
void *realloc(void *ptr, size_t size);
// Function definition
void free(void *ptr);
malloc: allocatessizebytes, does not initializecalloc: allocatescount*sizebytes, initializes all to 0realloc: resizes previously allocated memory, may move the addressfree: releases memory
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>
// Function definition
int main(void) {
// Variable declaration
int *arr = calloc(5, sizeof(int));
// Conditional check
if (arr == NULL) {
// Return result
return 1;
}
// For loop
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
// Variable declaration
int *new_arr = realloc(arr, 10 * sizeof(int));
// Conditional check
if (new_arr == NULL) {
// Dynamic memory operation
free(arr);
// Return result
return 1;
}
arr = new_arr;
// For loop
for (int i = 5; i < 10; i++) {
arr[i] = i * 10;
}
// For loop
for (int i = 0; i < 10; i++) {
// I/O operation
printf("%d ", arr[i]);
}
// I/O operation
printf("\n");
// Dynamic memory operation
free(arr);
// Return result
return 0;
}
0 10 20 30 40 50 60 70 80 90
realloc fails, it returns NULL but the original memory is not freed! So you must use a temporary variable to receive realloc's return value — on failure, you can still free the original memory.
(4) Sorting and Searching
qsort
// Function definition
void qsort(void *base, size_t count, size_t size,
int (*compare)(const void *, const void *));
Comparison function rules: return negative if a < b, 0 if equal, positive if a > b.
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>
// Preprocessor directive
#include <string.h>
// Function definition
int cmp_int(const void *a, const void *b) {
// Return result
return *(const int *)a - *(const int *)b;
}
// Function definition
int cmp_str(const void *a, const void *b) {
// Return result
return strcmp(*(const char **)a, *(const char **)b);
}
// Function definition
int main(void) {
int nums[] = {42, 17, 8, 95, 3, 61};
// Variable declaration
int n = sizeof(nums) / sizeof(nums[0]);
qsort(nums, n, sizeof(int), cmp_int);
// For loop
for (int i = 0; i < n; i++) {
// I/O operation
printf("%d ", nums[i]);
}
// I/O operation
printf("\n");
const char *names[] = {"Alice", "Bob", "Charlie", "Diana"};
// Variable declaration
int m = sizeof(names) / sizeof(names[0]);
qsort(names, m, sizeof(char *), cmp_str);
// For loop
for (int i = 0; i < m; i++) {
// I/O operation
printf("%s ", names[i]);
}
// I/O operation
printf("\n");
// Return result
return 0;
}
3 8 17 42 61 95
Alice Bob Charlie Diana
bsearch
// Function definition
void *bsearch(const void *key, const void *base, size_t count,
size_t size, int (*compare)(const void *, const void *));
Performs binary search on a sorted array. Returns a pointer to the found element, or NULL if not found.
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <stdlib.h>
// Function definition
int cmp_int(const void *a, const void *b) {
// Return result
return *(const int *)a - *(const int *)b;
}
// Function definition
int main(void) {
int nums[] = {3, 8, 17, 42, 61, 95};
// Variable declaration
int n = sizeof(nums) / sizeof(nums[0]);
// Variable declaration
int key = 42;
// Variable declaration
int *result = bsearch(&key, nums, n, sizeof(int), cmp_int);
// Conditional check
if (result != NULL) {
// I/O operation
printf("Found %d at index %ld\n", key, result - nums);
} else {
// I/O operation
printf("%d not found\n", key);
}
// Return result
return 0;
}
Found 42 at index 3
3. time.h Time Handling
(1) Time Functions
| Function/Type | Purpose |
|---|---|
time_t |
Time type (usually seconds since 1970-01-01) |
time(&t) |
Get current time |
clock() |
Get CPU clock ticks used by program |
localtime() |
Convert to local time struct |
gmtime() |
Convert to UTC time struct |
strftime() |
Format time as string |
difftime() |
Calculate difference between two times (seconds) |
(2) struct tm
// Struct/enum/union definition
struct tm {
// Variable declaration
int tm_sec;
// Variable declaration
int tm_min;
// Variable declaration
int tm_hour;
// Variable declaration
int tm_mday;
// Variable declaration
int tm_mon;
// Variable declaration
int tm_year;
// Variable declaration
int tm_wday;
// Variable declaration
int tm_yday;
// Variable declaration
int tm_isdst;
};
tm_mon ranges from 0-11 (0 = January), tm_year is the number of years since 1900, and tm_wday uses 0 for Sunday.
▶ Example
▶ Try it YourselfCurrent time: 2025-03-15 14:30:22
Today is day 6 of the week (0=Sun)
(3) Program Timing
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <time.h>
// Function definition
int main(void) {
clock_t start = clock();
volatile long sum = 0;
// For loop
for (long i = 0; i < 100000000L; i++) {
sum += i;
}
clock_t end = clock();
// Variable declaration
double elapsed = (double)(end - start) / CLOCKS_PER_SEC;
// I/O operation
printf("Elapsed: %.3f seconds\n", elapsed);
// Return result
return 0;
}
Elapsed: 0.235 seconds
clock() measures CPU time, not wall-clock time. If the program has sleep or I/O waits, that time is not counted. Use difftime to measure actual elapsed time.
4. ctype.h Character Handling
| Function | Test Condition |
|---|---|
isalpha(c) |
Letter |
isdigit(c) |
Digit |
isalnum(c) |
Letter or digit |
isupper(c) |
Uppercase letter |
islower(c) |
Lowercase letter |
isspace(c) |
Whitespace (space, tab, newline, etc.) |
ispunct(c) |
Punctuation |
isprint(c) |
Printable character |
toupper(c) |
Convert to uppercase |
tolower(c) |
Convert to lowercase |
These functions require an unsigned char value or EOF as their argument. Passing a negative char value is undefined behavior.
▶ Example
Count letters, digits, and other characters in a string:
▶ Try it YourselfLetters: 10, Digits: 3, Others: 6
5. assert.h Assertions
// Function definition
void assert(int expression);
When the expression is false, the program terminates and prints an error message (file name, line number, expression). Defining the NDEBUG macro before #include <assert.h> disables all assertions.
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include <assert.h>
// Function definition
double safe_divide(double a, double b) {
assert(b != 0 && "Divisor cannot be zero");
// Return result
return a / b;
}
// Function definition
int main(void) {
// I/O operation
printf("10 / 2 = %.1f\n", safe_divide(10.0, 2.0));
// I/O operation
printf("10 / 0 = %.1f\n", safe_divide(10.0, 0.0));
// Return result
return 0;
}
10 / 2 = 5.0
Assertion failed: b != 0 && "Divisor cannot be zero", file main.c, line 5
assert gets printed, so writing "Divisor cannot be zero" is more effective than a comment — when the assertion fails, you can immediately see the reason.
❓ FAQ
📖 Summary
math.hprovides math functions; trig functions use radians; compile with-lmrand/srandgenerate pseudo-random numbers; usesrand(time(NULL))to seed with timestrtol/strtodare safer thanatoi/atofand can detect conversion errorsqsort/bsearchare the standard library's sorting and searching tools, requiring custom comparison functionsassertis for development debugging; disable in release builds viaNDEBUG
📝 Exercises
- Write a program that generates 100 random integers from 1 to 1000, sorts them with qsort, and outputs the maximum and minimum values
- Write a program that uses clock() to compare the time difference between bubble sort and qsort on 10,000 integers
- Write a function that uses ctype.h functions to implement string case conversion (input a string, output all-uppercase and all-lowercase versions)