1 / 15

C Standard Library

stdio.h, ctype.h, stdlib.h, assert.h, stdarg.h, time.h

Unit VI: Preprocessor, Macro, Static and Shared Library

Lecture 24

Instructor: Mohsin F. Dar
Assistant Professor
BTech First Semester - C Programming

📚 What is the C Standard Library?

The C Standard Library is a collection of pre-written functions, macros, and type definitions that come with every C compiler.

Key Characteristics:

💡 Remember: You don't need to write these functions yourself - just include the appropriate header file!

📂 C Standard Library Headers

Header File Purpose
stdio.h Standard Input/Output operations
ctype.h Character type testing and conversion
stdlib.h General utilities: memory, conversions, etc.
string.h String manipulation functions
math.h Mathematical functions
time.h Date and time functions
assert.h Debugging assertions
stdarg.h Variable argument lists

📝 stdio.h - Standard Input/Output

Most commonly used header file for input and output operations.

Common Functions:

printf()
Formatted output to console
scanf()
Formatted input from console
fprintf(), fscanf()
Formatted I/O with files
fopen(), fclose()
Open and close files
fread(), fwrite()
Binary file operations

💻 stdio.h - Code Example

                #include <stdio.h>

                int main() {
                    FILE *fp;
                    char name[50];
                    int age;
                    
                    // Console I/O
                    printf("Enter name: ");
                    scanf("%s", name);
                    
                    // File operations
                    fp = fopen("data.txt", "w");
                    if(fp != NULL) {
                        fprintf(fp, "Name: %s\n", name);
                        fclose(fp);
                    }
                    
                    return 0;
                }
                

🔤 ctype.h - Character Type Functions

Functions for testing and converting character types.

Testing Functions:

isalpha()
Check if alphabetic
isdigit()
Check if digit (0-9)
isalnum()
Check if alphanumeric
isspace()
Check if whitespace

Conversion Functions:

toupper()
Convert to uppercase
tolower()
Convert to lowercase

💻 ctype.h - Code Example

                #include <stdio.h>
                #include <ctype.h>

                int main() {
                    char ch = 'a';
                    char str[] = "Hello123";
                    
                    // Testing characters
                    if(isalpha(ch))
                        printf("'%c' is alphabetic\n", ch);
                    
                    // Converting case
                    printf("Uppercase: %c\n", toupper(ch));
                    
                    // Checking string characters
                    for(int i = 0; str[i] != '\0'; i++) {
                        if(isdigit(str[i]))
                            printf("%c is a digit\n", str[i]);
                    }
                    
                    return 0;
                }
                

🛠️ stdlib.h - General Utilities

Provides general purpose functions including memory management, conversions, and more.

Memory Management:

malloc()
Allocate memory dynamically
calloc()
Allocate and initialize memory to zero
realloc()
Resize previously allocated memory
free()
Deallocate memory

🛠️ stdlib.h - More Functions

String Conversion:

atoi()
Convert string to integer
atof()
Convert string to float

Random Numbers:

rand()
Generate random number
srand()
Seed random number generator

Program Control:

exit()
Terminate program

💻 stdlib.h - Code Example

                #include <stdio.h>
                #include <stdlib.h>

                int main() {
                    // Dynamic memory allocation
                    int *arr = (int*)malloc(5 * sizeof(int));
                    
                    if(arr == NULL) {
                        printf("Memory allocation failed\n");
                        exit(1);
                    }
                    
                    // String to integer conversion
                    char str[] = "123";
                    int num = atoi(str);
                    printf("Number: %d\n", num);
                    
                    // Random number generation
                    srand(time(NULL));
                    printf("Random: %d\n", rand() % 100);
                    
                    free(arr);  // Free allocated memory
                    return 0;
                }
                

🐛 assert.h - Debugging Assertions

Used for debugging by testing assumptions in your code.

What is an Assertion?

An assertion is a statement that a condition must be true at a certain point in your program. If the condition is false, the program terminates with an error message.

assert(expression)
If expression is false, program terminates with diagnostic information

⚠️ Important: Assertions are typically disabled in production code by defining NDEBUG

💻 assert.h - Code Example

                #include <stdio.h>
                #include <assert.h>

                int divide(int a, int b) {
                    // Assert that divisor is not zero
                    assert(b != 0);
                    return a / b;
                }

                int main() {
                    int x = 10, y = 2;
                    
                    // This will work fine
                    printf("Result: %d\n", divide(x, y));
                    
                    // This will trigger assertion failure
                    // printf("Result: %d\n", divide(x, 0));
                    
                    return 0;
                }
                
// Output if assertion fails: // Assertion failed: b != 0, file test.c, line 5

📋 stdarg.h - Variable Argument Lists

Allows functions to accept a variable number of arguments.

Key Macros:

va_list
Type for storing variable argument information
va_start()
Initialize the va_list
va_arg()
Retrieve next argument
va_end()
Clean up the va_list

Example: The printf() function uses stdarg.h to accept variable number of arguments!

💻 stdarg.h - Code Example

                #include <stdio.h>
                #include <stdarg.h>

                // Function to calculate sum of variable numbers
                int sum(int count, ...) {
                    va_list args;
                    int total = 0;
                    
                    va_start(args, count);  // Initialize
                    
                    for(int i = 0; i < count; i++) {
                        total += va_arg(args, int);  // Get next arg
                    }
                    
                    va_end(args);  // Clean up
                    return total;
                }

                int main() {
                    printf("Sum of 3 numbers: %d\n", sum(3, 10, 20, 30));
                    printf("Sum of 5 numbers: %d\n", sum(5, 1, 2, 3, 4, 5));
                    return 0;
                }
                

⏰ time.h - Date and Time Functions

Functions for manipulating and formatting dates and times.

Key Functions:

time()
Get current calendar time
clock()
Get processor time
difftime()
Calculate difference between two times
localtime()
Convert time to local time structure
strftime()
Format time as string

💻 time.h - Code Example

                #include <stdio.h>
                #include <time.h>

                int main() {
                // Method 1: Using clock() to measure CPU time
                clock_t start = clock();
                
                // Some operation to measure
                long sum = 0;
                for (int i = 0; i < 1000000; i++) {
                for (int i = 0; i < 1000000; i++) {
                    sum += i;
                }
                
                clock_t end = clock();
                double cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
                
                printf("Sum: %ld\n", sum);
                printf("CPU time used: %f seconds\n", cpu_time_used);
                
                // Method 2: Using time() to get calendar time
                time_t current_time;
                time(¤t_time);
                printf("\nCurrent time: %s", ctime(¤t_time));
                
                return 0;
                }
                

cmath - Math Functions

Functions for mathematical operations.

Key Functions:

abs()
Absolute value
sqrt()
Square root
pow()
Power function
sin()
Sine function
cos()
Cosine function
tan()
Tangent function
log()
Natural logarithm
exp()
Exponential function
floor()
Floor value
ceil()
Ceiling value
round()
Round value
fmod()
Floating-point remainder
hypot()
Hypotenuse function
erf()
Error function
erfc()
Complementary error function
lgamma()
Logarithmic gamma function
tgamma()
Gamma function

💻 math.h - Code Example

                #include <stdio.h>
                #include <math.h>

                int main() {
                    double x = -5.5, y = 3.2;
                    double result;
                    
                    // Absolute value
                    result = abs(x);
                    printf("abs(%f) = %f\n", x, result);
                    
                    // Square root
                    result = sqrt(y);
                    printf("sqrt(%f) = %f\n", y, result);
                    
                    // Power function
                    result = pow(x, y);
                    printf("pow(%f, %f) = %f\n", x, y, result);
                    
                    // Sine function
                    result = sin(x);
                    printf("sin(%f) = %f\n", x, result);
                    
                    // Cosine function
                    result = cos(y);
                    printf("cos(%f) = %f\n", y, result);
                    
                    // Tangent function
                    result = tan(x);
                    printf("tan(%f) = %f\n", x, result);
                    
                    // Natural logarithm
                    result = log(y);
                    printf("log(%f) = %f\n", y, result);
                    
                    // Exponential function
                    result = exp(x);
                    printf("exp(%f) = %f\n", x, result);
                    
                    // Floor value
                    result = floor(y);
                    printf("floor(%f) = %f\n", y, result);
                    
                    // Ceiling value
                    result = ceil(x);
                    printf("ceil(%f) = %f\n", x, result);
                    
                    // Round value
                    result = round(y);
                    printf("round(%f) = %f\n", y, result);
                    
                    // Floating-point remainder
                    result = fmod(x, y);
                    printf("fmod(%f, %f) = %f\n", x, y, result);
                    
                    // Hypotenuse function
                    result = hypot(x, y);
                    printf("hypot(%f, %f) = %f\n", x, y, result);
                    
                    // Error function
                    result = erf(x);
                    printf("erf(%f) = %f\n", x, result);
                    
                    // Complementary error function
                    result = erfc(y);
                    printf("erfc(%f) = %f\n", y, result);
                    
                    // Logarithmic gamma function
                    result = lgamma(x);
                    printf("lgamma(%f) = %f\n", x, result);
                    
                    // Gamma function
                    result = tgamma(y);
                    printf("tgamma(%f) = %f\n", y, result);
                    
                    return 0;
                }
                

📝 Summary

stdio.h

  • Input/Output operations
  • File handling
  • Formatted I/O functions

stdlib.h

  • Memory allocation
  • String conversion
  • Random number generation

string.h

  • String manipulation
  • Memory operations
  • String comparison

math.h

  • Mathematical functions
  • Trigonometric functions
  • Logarithmic functions

time.h

  • Date and time functions
  • Time manipulation
  • Format conversion

ctype.h

  • Character handling
  • Type checking
  • Case conversion

Key Takeaways

  • Standard Library provides essential functions for common tasks
  • Memory management is crucial in C programming
  • Always check return values for error handling
  • Use appropriate headers for required functionality