Command-line arguments are a powerful feature in C programming that allow users to pass information to a program when it starts. They provide a flexible way to customize program behavior without modifying the source code.
In C, command-line arguments are passed to the main()
function. The function signature typically looks like this:
int main(int argc, char *argv[])
Here, argc
(argument count) represents the number of arguments, and argv
(argument vector) is an array of strings containing the arguments.
You can access command-line arguments using array notation. The first element, argv[0]
, always contains the program name itself.
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Program name: %s\n", argv[0]);
for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Command-line arguments are passed as strings. To use them as other data types, you'll need to convert them. The C Standard Library provides functions for this purpose:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <num1> <num2>\n", argv[0]);
return 1;
}
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
printf("Sum: %d\n", num1 + num2);
return 0;
}
Proper error handling is crucial when working with command-line arguments. Always check for potential errors and provide meaningful feedback to the user.
Command-line arguments enhance the flexibility and usability of C programs. By mastering this concept, you can create more versatile and user-friendly applications. Remember to handle arguments carefully and provide clear documentation for your program's usage.