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 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 , 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 charactersstrncat(): Concatenates up to charactersstrncmp(): Compares up to charactersstrchr(): Finds first occurrence of characterstrrchr(): Finds last occurrence of characterstrstr(): 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 :
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 letterislower(c): Tests if lowercase letterisprint(c): Tests if printable characterisgraph(c): Tests if printable but not spaceispunct(c): Tests if punctuationiscntrl(c): Tests if control characterisxdigit(c): Tests if hexadecimal digit (0-9, A-F, a-f)
Case Conversion Functions
toupper(c): Returns uppercase equivalent; returns original if not lowercasetolower(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 ≥floor(x): Returns largest integer ≤round(x): Rounds to nearest integer
Absolute Value and Roots
fabs(x): Returns absolute value ofsqrt(x): Returns square root of
Exponential and Logarithmic Functions
pow(x, y): Returnsexp(x): Returnslog(x): Returns natural logarithm oflog10(x): Returns base-10 logarithm of
Trigonometric Functions
sin(x): Returns sine of (in radians)cos(x): Returns cosine of (in radians)tan(x): Returns tangent of (in radians)
Important: All trigonometric functions use radians, not degrees. Convert degrees to radians by multiplying by .
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 to integeratol(s): Converts string to long integeratof(s): Converts string 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 and
RAND_MAX(inclusive) - RAND_MAX: Compiler-dependent constant, guaranteed ≥
- 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
- Call
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)