C documentation V1 Help

Command Line Arguments

Command line arguments allow a C program to accept inputs directly from the command line when it is executed. These arguments provide a flexible way to pass information to a program without requiring user interaction during runtime.

Using Command Line Arguments

In C, the main function can receive command line arguments through its parameters. The standard signature for the main function that accepts command line arguments is:

int main(int argc, char *argv[]) { // Code that uses command line arguments return 0; }

Here, argc (argument count) represents the number of command line arguments, and argv (argument vector) is an array of strings containing the actual arguments.

Example: Printing Command Line Arguments

Let's create a simple program that prints the command line arguments.

#include <stdio.h> int main(int argc, char *argv[]) { // Check if there are any command line arguments if (argc > 1) { // Print each argument for (int i = 1; i < argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } } else { printf("No command line arguments provided.\n"); } return 0; }

In this example, the program checks if there are any command line arguments. If arguments are present, it iterates through them and prints each one along with its position.

Running the Program

To run the program with command line arguments, compile it and provide the arguments after the executable name.

./program_name arg1 arg2 arg3

In the above command, program_name is the name of the compiled executable, and arg1, arg2, arg3 are the command line arguments.

Conclusion

Command line arguments provide a means for C programs to receive input directly from the command line, enabling more dynamic and versatile interactions. This capability is especially useful for scripts, utilities, and applications that need to adapt to different scenarios based on user inputs.

In the upcoming sections, we'll explore more advanced topics in C programming. If you have specific questions or areas you'd like to delve into further, feel free to ask. Happy coding!

Last modified: 25 February 2024