Skip to main content

Chapter Summary

This chapter introduces students to four essential C standard libraries that provide pre-built functions for common programming tasks. Understanding these libraries enables more efficient and safer code development.

string.h Library

The string.h library provides functions for manipulating C-strings (null-terminated character arrays). Key functions include:

strcpy() - String Copy

  • Purpose: Copies one string to another, including the null terminator
  • Syntax: strcpy(destination, source)
  • Important: Programmer must ensure destination is large enough to hold source
  • Example:
    char dest[10];
    strcpy(dest, "hello"); // dest now contains "hello"

strcmp() - String Compare

  • Purpose: Compares two strings lexically (alphabetically)
  • Return Values:
    • Returns 00 if strings are identical
    • Returns negative value if first string is lexically earlier
    • Returns positive value if first string is lexically later
  • Critical: Always compare return value against 00, not strings directly
  • Correct Usage:
    if (strcmp(s1, s2) == 0)      // s1 equals s2
    if (strcmp(s1, s2) < 0) // s1 is lexically earlier
    if (strcmp(s1, s2) > 0) // s1 is lexically later

strlen() - String Length

  • Purpose: Returns number of characters before null terminator
  • Performance Consideration: Function must scan entire string to find \0, making it slow for long strings
  • Best Practice: Call strlen() once before loops, not inside loop conditions
  • Example - Efficient:
    int length = strlen(str);
    for (i = 0; i < length; i++) { ... }
  • Example - Inefficient (AVOID):
    for (i = 0; i < strlen(str); i++) { ... }  // strlen() called every iteration

strcat() - String Concatenate

  • Purpose: Appends second string to end of first string
  • Syntax: strcat(destination, source)
  • Important: Destination must be large enough to hold both strings
  • Example:
    char s1[20] = "hello";
    strcat(s1, "world"); // s1 now contains "helloworld"

Additional string.h Functions

  • strncpy(): Copies up to nn characters
  • strncat(): Concatenates up to nn characters
  • strncmp(): Compares up to nn characters
  • strchr(): Finds first occurrence of character
  • strrchr(): Finds last occurrence of character
  • strstr(): Finds first occurrence of substring

ctype.h Library

The ctype.h library provides functions to test character properties and perform case conversion.

Character Testing Functions

All return truthy (non-zero) if condition is true, falsey (zero) if false. Always test against 00:

  • isalpha(c): Tests if alphabetic (A-Z, a-z)
  • isdigit(c): Tests if digit (0-9)
  • isalnum(c): Tests if alphanumeric (letter or digit)
  • isspace(c): Tests if whitespace (space, tab, newline)
  • isupper(c): Tests if uppercase letter
  • islower(c): Tests if lowercase letter
  • isprint(c): Tests if printable character
  • isgraph(c): Tests if printable but not space
  • ispunct(c): Tests if punctuation
  • iscntrl(c): Tests if control character
  • isxdigit(c): Tests if hexadecimal digit (0-9, A-F, a-f)

Case Conversion Functions

  • toupper(c): Returns uppercase equivalent; returns original if not lowercase
  • tolower(c): Returns lowercase equivalent; returns original if not uppercase

Critical Concept: Pass-by-Value

toupper() and tolower() use pass-by-value, meaning they do not modify the original character. The return value must be captured:

char lowerA = 'a';
char upperA = toupper(lowerA); // Must capture return value
// lowerA is still 'a', upperA is now 'A'

math.h Library

The math.h library provides common mathematical functions:

Rounding Functions

  • ceil(x): Returns smallest integer ≥ xx
  • floor(x): Returns largest integer ≤ xx
  • round(x): Rounds xx to nearest integer

Absolute Value and Roots

  • fabs(x): Returns absolute value of xx
  • sqrt(x): Returns square root of xx

Exponential and Logarithmic Functions

  • pow(x, y): Returns xyx^y
  • exp(x): Returns exe^x
  • log(x): Returns natural logarithm of xx
  • log10(x): Returns base-10 logarithm of xx

Trigonometric Functions

  • sin(x): Returns sine of xx (in radians)
  • cos(x): Returns cosine of xx (in radians)
  • tan(x): Returns tangent of xx (in radians)

Important: All trigonometric functions use radians, not degrees. Convert degrees to radians by multiplying by π/180\pi/180.

stdlib.h Library

The stdlib.h library contains general-purpose functions. This chapter focuses on string conversion and random number generation.

String to Number Conversion

  • atoi(s): Converts string ss to integer
  • atol(s): Converts string ss to long integer
  • atof(s): Converts string ss to double (floating-point)

Example:

int x = atoi("42");        // x = 42
double y = atof("3.14"); // y = 3.14

Pseudo-Random Number Generation

rand() Function

  • Purpose: Returns pseudo-random integer between 00 and RAND_MAX (inclusive)
  • RAND_MAX: Compiler-dependent constant, guaranteed ≥ 3276732767
  • Behavior: Without seeding, generates same sequence every program run

srand() Function - Seeding

  • Purpose: Sets starting point (seed) for random number sequence
  • Syntax: srand(seed_value)
  • Key Points:
    • Call srand() exactly once at program start
    • Different seeds produce different sequences
    • Same seed always produces same sequence
    • Use srand(time(NULL)) for different sequence each run

Example - Reproducible (for debugging):

srand(42);  // Fixed seed for consistent results
for (i = 0; i < 5; i++) {
printf("%d\n", rand());
}

Example - Different Each Run:

#include <time.h>
srand(time(NULL)); // Seed with current time
for (i = 0; i < 5; i++) {
printf("%d\n", rand());
}

Understanding Pseudo-Random Generators

  • Random number generators are not truly random but follow a deterministic sequence
  • The seed determines which point in the sequence to start
  • Calling srand() multiple times is unnecessary and can produce unexpected results
  • For debugging, use fixed seed; for production, use time(NULL)