ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Other Topics: Variable Length Argument List, Using Command Line Arguments
    Programming FundamentalsTopic 34 of 39

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

    7 minread
    1,131words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,131
      Code examples0
      DifficultyIntermediate