C CLI Arguments

C CLI Arguments – Learn to Handle Command-Line Inputs

In C, command-line arguments allow you to pass data to your program directly from the terminal. These arguments can be used to influence the behavior of your program without the need for user input during execution.

๐Ÿ”น What are CLI Arguments?

Command-line arguments are parameters passed to your program when you run it from the terminal or command prompt. These arguments are passed to the main() function, which can access them through the argc (argument count) and argv (argument vector) parameters.

๐Ÿ“ Syntax of CLI Arguments

The main() function can accept two arguments:

  • int argc: The number of arguments passed to the program, including the program’s name.
  • char *argv[]: An array of strings (character arrays) that holds the actual arguments.

๐Ÿ“ Example 1: Using CLI Arguments

In this example, the program prints the number of arguments passed and the arguments themselves.

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Number of arguments: %d\n", argc);
    printf("Arguments passed:\n");
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }
    return 0;
}

Try It Now

๐Ÿ”น Explanation

  • argc gives the total number of arguments passed to the program.
  • argv[] is an array where each element is a string representing an individual argument. The first element (argv[0]) is always the name of the program.

๐Ÿ”น Example 2: Using CLI Arguments to Perform Calculations

Here, we pass two numbers as command-line arguments and perform a simple addition.

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

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Please provide exactly two numbers.\n");
        return 1;
    }
    
    int num1 = atoi(argv[1]);
    int num2 = atoi(argv[2]);
    
    printf("Sum: %d\n", num1 + num2);
    return 0;
}

Try It Now

๐Ÿ”น Explanation

  • We check if the user has provided exactly two arguments (other than the program name) using argc.
  • atoi() is used to convert the string arguments into integers for calculation.

๐ŸŽฏ Key Takeaways

  • argc: Represents the number of arguments passed to the program.
  • argv[]: Array of strings representing the arguments passed to the program.
  • CLI arguments are passed to the main() function and can be used for dynamic input without requiring interaction during execution.

๐Ÿ“ Practice Time!

Try passing different arguments to your program and experiment with various operations to handle them. You can also modify the program to perform different tasks based on the command-line input.