The arguments passed from command line are called command line arguments. These arguments are handled by main() function.

 

 

When you execute a C program from the command line, you can often pass additional information to the program. This information is known as command line arguments. These arguments can be used to customize the program’s behavior or provide input data.

Syntax

The main function in C can be declared to accept command line arguments. The general syntax is:

int main(int argc, char *argv[]) {
    // ...
}
  • argc: This is an integer that represents the total number of arguments passed to the program, including the program name itself.
  • argv: This is a pointer to an array of strings. Each element in the array contains one command-line argument. The first element (argv[0]) always contains the name of the program.

Example:

#include <stdio.h>

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

If you save this code as hello.c and compile it, you can run it with different arguments:

./hello

This will output:

Number of arguments: 1
Argument 0: ./hello

If you run it with arguments:

./hello world 123

The output will be:

Number of arguments: 3
Argument 0: ./hello
Argument 1: world
Argument 2: 123

Command line arguments are a powerful way to pass parameters to a program when it is executed. They allow users to customize the behavior of the program without modifying its source code.

Command-line arguments are handled by the main() function of a C program. To pass command-line arguments, we typically define main() with two arguments: the first argument is the number of command-line arguments and the second is a list of command-line arguments.

 

Common Uses of Command Line Arguments

  • Providing input data: For example, a program that calculates the area of a circle might take the radius as a command-line argument.
  • Controlling program behavior: A program might have different modes of operation, which can be selected using command-line flags (e.g., -h for help, -v for verbose output).
  • Passing configuration options: A program can be configured using command-line options, such as specifying a file path or setting a timeout value.

By understanding and effectively using command-line arguments, you can create more flexible and powerful C programs.

Related Posts

Leave a Reply