C: The Standard Library

🗓 Last updated: 2026-11-30👤 Written by: Harper✓ Reviewed by: Dana🏷 Category: C Tutorial

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.

Reference entries in this section: rand() srand atoi strtol malloc calloc realloc free char

1. math.h Mathematical Operations

Using math functions requires including the header and linking the math library:

C
// 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
⚠️ Note: Trigonometric functions take radians, not degrees! To convert degrees to radians: rad = deg * 3.14159265 / 180.0.

▶ Example

Calculate the distance between two points:

▶ Try it Yourself
TEXT
Distance: 5.00

2. stdlib.h General Utilities

(1) Random Numbers

C
// 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.

C
// 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;
}
TEXT
1804289383 846930886 1681692777 1714636915 1957747793
83 86 77 15 93
⚠️ Note: 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)
C
// 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;
}
TEXT
a = 42
b = 3.14
c = 255
d = 123, Unconverted part: abc
💡 Tip: 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

C
// 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);
C
// 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;
}
TEXT
0 10 20 30 40 50 60 70 80 90
⚠️ Note: When 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

C
// 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.

C
// 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;
}
TEXT
3 8 17 42 61 95
Alice Bob Charlie Diana

bsearch

C
// 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.

C
// 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;
}
TEXT
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

C
// 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 Yourself
TEXT
Current time: 2025-03-15 14:30:22
Today is day 6 of the week (0=Sun)

(3) Program Timing

C
// 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;
}
TEXT
Elapsed: 0.235 seconds
⚠️ Note: 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 Yourself
TEXT
Letters: 10, Digits: 3, Others: 6

5. assert.h Assertions

C
// 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.

C
// 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;
}
TEXT
10 / 2 = 5.0
Assertion failed: b != 0 && "Divisor cannot be zero", file main.c, line 5
💡 Tip: The string literal in 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.

Reference entries in this section: rand() srand atoi strtol malloc calloc realloc free char

❓ FAQ

Q How to generate a random int in C?
A rand() from stdlib.h returns an integer between 0 and RAND_MAX. Call srand((unsigned)time(NULL)) once at the start of your program to seed the generator with the current time — otherwise you get the same sequence every run. To get a range like [1, 100], use 1 + rand() % 100.
Q What is the printf format specifier for bool?
A C has no native bool in C89, and even in C99 stdbool.h, printf has no format specifier for bool values. The standard practice is to print as an integer with %d, or to manually map true to "true" and false to "false" in a conditional before printing.
Q Difference between malloc and calloc?
A malloc(bytes) allocates uninitialized memory — the contents are whatever was left there before. calloc(n, element_size) allocates n times element_size bytes and zeroes every byte. calloc is slightly slower but safer when you need the memory to start at all zeros, such as string buffers or arrays.
Q How do function pointers in C work?
A A function pointer stores the address of a function. You declare one with return_type (*name)(param_types), assign it with name = &my_func (or just name = my_func), and call it with (*name)(args) or name(args). The qsort comparison function in this very tutorial is the most common practical use of function pointers in C.
Q Should I cast the result of malloc (in C)?
A No. malloc returns void *, which C automatically converts to any pointer type. Casting makes no difference to correctness and is considered redundant in pure C. Only C++ requires the cast.
Q Why should ctype.h function arguments be cast to unsigned char?
A If char is signed, characters with the high bit set may be negative values (e.g. value 0xFF becomes -1). Passing negative values to ctype functions like isdigit or isalpha is undefined behavior. Cast to unsigned char to ensure the value is always in the 0-255 range.
Q What is the difference between ++i and i++?
A Both increment i by 1, but they return different values. ++i (pre-increment) increments first, then returns the new value. i++ (post-increment) returns the old value, then increments. In a for loop like for (int i = 0; i < n; i++) the final value is thrown away anyway, so either is fine.
Q What is the difference between assert and an if check?
A assert is for logic errors that should never happen during development and disappears entirely when NDEBUG is defined. An if check handles runtime errors that might actually occur in production and is always compiled in. If the condition should never be true, use assert. If it can happen, use if.

📖 Summary

📝 Exercises

  1. Write a program that generates 100 random integers from 1 to 1000, sorts them with qsort, and outputs the maximum and minimum values
  2. Write a program that uses clock() to compare the time difference between bubble sort and qsort on 10,000 integers
  3. Write a function that uses ctype.h functions to implement string case conversion (input a string, output all-uppercase and all-lowercase versions)
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏