ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Variable Arguments Com…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 34 of 39
    Topic Study Note Illustration
    34

    Other Topics: Variable Length Argument List, Using Command Line Arguments

    In C, there are advanced features that allow you to handle situations where the number of arguments passed to a function is not fixed. These features are...

    Variable Length Argument List and Using Command Line Arguments in C

    In C, there are advanced features that allow you to handle situations where the number of arguments passed to a function is not fixed. These features are Variable Length Argument Lists and Command Line Arguments. Let’s explore both of these in detail.


    1. Variable Length Argument List

    In C, it is sometimes necessary to write functions that can accept a variable number of arguments. This is especially useful when you don't know the exact number of arguments that will be passed to the function at the time of writing it (such as with functions like printf or scanf). To handle such cases, C provides a feature known as variable-length argument lists.

    Standard Header: <stdarg.h>

    To work with variable-length argument lists, you need to include the stdarg.h header file, which defines a set of macros to handle such arguments.

    Key Macros in <stdarg.h>:

    • va_start: Initializes a va_list to access the variable arguments.
    • va_arg: Retrieves the next argument in the list.
    • va_end: Cleans up after accessing the arguments.
    • va_copy: Copies an existing va_list to another.

    Function Syntax:

    #include <stdarg.h>
    
    return_type function_name(data_type fixed_arg, ...);
    

    Where fixed_arg is a regular argument, and ... represents the variable-length argument list.

    Example: A Simple sum Function with Variable Arguments:

    #include <stdio.h>
    #include <stdarg.h>
    
    // Function to calculate the sum of a variable number of integers
    int sum(int num, ...) {
        va_list args;
        int total = 0;
    
        // Initialize va_list to access the variable arguments
        va_start(args, num);
    
        // Loop through the arguments and sum them
        for (int i = 0; i < num; i++) {
            total += va_arg(args, int);  // Get the next argument
        }
    
        // Clean up the va_list
        va_end(args);
    
        return total;
    }
    
    int main() {
        printf("Sum of 2, 3, 4: %d\n", sum(3, 2, 3, 4));  // Outputs 9
        printf("Sum of 5, 10, 15, 20: %d\n", sum(4, 5, 10, 15, 20));  // Outputs 50
        return 0;
    }
    

    Explanation:

    • sum(int num, ...): The function sum takes a fixed integer argument num (which tells how many numbers will follow) and then the variable number of arguments, denoted by ....
    • va_list args: This defines a variable args of type va_list that will be used to access the variable arguments.
    • va_start(args, num): Initializes the va_list args to point to the first variable argument (after num).
    • va_arg(args, int): Retrieves the next argument of type int from the args list.
    • va_end(args): Cleans up after the variable arguments are processed.

    2. Using Command Line Arguments

    In C, programs can accept input from the command line at the time of execution. This is done using command-line arguments. When a C program is executed, the operating system passes command-line arguments to the program. These arguments are typically used to provide inputs such as file names, flags, or configuration options.

    Function Syntax:

    When you define the main function, you can accept command-line arguments by using two parameters:

    int main(int argc, char *argv[])
    
    • argc (argument count): An integer that represents the number of command-line arguments passed to the program, including the program name.
    • argv (argument vector): An array of strings (character pointers) representing the actual arguments passed. argv[0] is the name of the program, and argv[1] to argv[argc-1] are the user-provided arguments.

    Example: Simple Command Line Argument Program

    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
        printf("Number of arguments: %d\n", argc);  // Prints the number of arguments
        printf("Program name: %s\n", argv[0]);      // Prints the program name
    
        // Loop through each command-line argument and print it
        for (int i = 1; i < argc; i++) {
            printf("Argument %d: %s\n", i, argv[i]);
        }
    
        return 0;
    }
    

    Explanation:

    • argc gives the number of arguments passed to the program, including the program's name.
    • argv[] is an array of strings where each element is a command-line argument.
    • argv[0] is always the name of the program.
    • argv[1], argv[2], ... are the actual arguments passed by the user.

    Example Command Line Execution:

    Assume the above code is saved in a file named cmd_args.c, and it is compiled to an executable named cmd_args. You can run the program like this:

    ./cmd_args arg1 arg2 arg3
    

    Output:

    Number of arguments: 4
    Program name: ./cmd_args
    Argument 1: arg1
    Argument 2: arg2
    Argument 3: arg3
    

    Explanation:

    • The program prints the total number of arguments passed (argc), the name of the program (argv[0]), and the additional arguments provided by the user (argv[1], argv[2], etc.).

    Practical Use Case of Command-Line Arguments:

    Command-line arguments are often used in scenarios like:

    • Specifying input/output file names.
    • Configuring settings (e.g., verbosity, mode of operation).
    • Passing flags (e.g., -v for verbose, -h for help).

    Example: File Operation Program

    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
        if (argc != 3) {
            printf("Usage: %s <source_file> <destination_file>\n", argv[0]);
            return 1;
        }
    
        FILE *source = fopen(argv[1], "r");
        FILE *destination = fopen(argv[2], "w");
    
        if (source == NULL) {
            perror("Error opening source file");
            return 1;
        }
        if (destination == NULL) {
            perror("Error opening destination file");
            return 1;
        }
    
        char ch;
        while ((ch = fgetc(source)) != EOF) {
            fputc(ch, destination);
        }
    
        fclose(source);
        fclose(destination);
    
        printf("File copy successful!\n");
    
        return 0;
    }
    

    Explanation:

    • This program accepts two command-line arguments: the source file and the destination file.
    • It checks if exactly two arguments are provided (aside from the program name).
    • It then opens the source file for reading and the destination file for writing.
    • The program reads from the source file and writes to the destination file character by character, performing a simple file copy operation.

    Summary of Concepts

    Concept Description
    Variable Length Arguments Functions can accept a variable number of arguments using macros from <stdarg.h>. va_start, va_arg, and va_end are key for processing.
    Command Line Arguments argc and argv[] allow programs to accept arguments from the command line. argc is the number of arguments, and argv[] holds the arguments as strings.

    Conclusion

    Both variable-length argument lists and command-line arguments are essential features in C that provide flexibility and enhance the interactivity of programs. The use of stdarg.h allows a function to accept an arbitrary number of arguments, and command-line arguments provide a powerful way for users to interact with a program at runtime, making it more dynamic and configurable.

    ← Previous topic 33
    # and ## Operators, Predefined Symbolic Constants, Assertions
    Next topic 35 →
    Compiling Multiple-Source-File Programs, Program Termination with exit and atexit

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals