Command-Line Arguments in C
Command-line arguments are a way to pass input parameters to your program when it starts. These arguments are passed to the main()
function of your program via parameters, enabling you to customize the behavior of the program based on user input.
At SamagraCS Educational Technology, we’ll guide you through understanding command-line arguments in C, provide a program example, and explain how to run the program with command-line arguments on Windows using the Command Prompt.
What Are Command-Line Arguments?
Command-line arguments allow the user to pass values to the program when it is executed from the command line. In C, these arguments are passed to the main()
function through two parameters:
int argc
: Argument count (number of command-line arguments, including the program name).char *argv[]
: Argument vector (an array of strings representing the actual arguments).
Syntax of main()
with Command-Line Arguments:
int main(int argc, char *argv[]) {
// Your code here
}
argc
: Number of arguments passed. The first argument (index 0) is always the program name.argv[]
: Array of strings (character pointers), where each element contains one argument.
Command-Line Arguments Program Example
Let’s write a simple program that demonstrates the use of command-line arguments. The program will take two numbers as arguments, perform a basic operation (e.g., addition), and print the result.
Program:
#include <stdio.h>
#include <stdlib.h> // For atoi (convert string to int)
int main(int argc, char *argv[]) {
// Check if the correct number of arguments is provided
if (argc != 3) {
printf("Usage: %s <num1> <num2>\n", argv[0]);
return 1; // Exit with error code
}
// Convert arguments from strings to integers
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
// Perform addition
int sum = num1 + num2;
// Print the result
printf("Sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
Explanation:
- The program expects two arguments from the user:
num1
andnum2
. - The
argc
variable is checked to ensure the correct number of arguments are provided. - The arguments
argv[1]
andargv[2]
are converted from strings to integers usingatoi()
. - The program then calculates the sum of the two numbers and prints the result.
Steps to Run the Program with Command-Line Arguments on Windows
Step 1: Save the Program
Save the above program as cmd_args_example.c
.
Step 2: Open the Command Prompt
- Press
Win + R
, typecmd
, and press Enter to open the Command Prompt window. - Navigate to the directory where your C file is saved. Use the
cd
command to change directories:
cd path\to\your\directory
Step 3: Compile the Program
Use the gcc
command to compile the program if you have GCC installed. You can install MinGW (Minimalist GNU for Windows) if you don’t have it.
- Compile the program using the following command:
gcc cmd_args_example.c -o cmd_args_example
This will create an executable file named cmd_args_example.exe
.
Step 4: Run the Program with Command-Line Arguments
After compiling, run the program by passing two arguments:
- Command to run the program:
cmd_args_example 5 10
This command passes the numbers 5
and 10
as arguments to the program. The output will be:
Sum of 5 and 10 is 15
Step 5: Running the Program with Incorrect Arguments
Try running the program without passing any arguments or with too many arguments:
- Command:
cmd_args_example
Output:
Usage: cmd_args_example <num1> <num2>
The program checks for the correct number of arguments using argc
and prints a usage message if the user doesn’t provide exactly two arguments.
Important Notes about Command-Line Arguments
- Argument Count (
argc
):
- The first argument (
argv[0]
) is always the program’s name. - In the example above, the
argc
value is 3, because the program expects two numbers plus the program name.
- Argument Vector (
argv[]
):
argv[]
is an array of strings, where each argument is stored as a string.- Use functions like
atoi()
,atof()
, orstrtol()
to convert string arguments to numeric values (integers, floats, etc.).
- Error Handling:
- Always check if the correct number of arguments is passed by comparing
argc
with the expected number of arguments. - Provide useful error messages or usage instructions to guide users when they input arguments incorrectly.
Additional Example: Multiple Command-Line Arguments
Here’s another example where the program accepts multiple arguments and calculates the sum of all numbers passed via the command line.
Program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
// Check if at least one number is passed
if (argc < 2) {
printf("Usage: %s <num1> <num2> ... <numN>\n", argv[0]);
return 1;
}
int sum = 0;
// Loop through the arguments and add them to the sum
for (int i = 1; i < argc; i++) {
sum += atoi(argv[i]);
}
// Print the result
printf("The sum of the numbers is: %d\n", sum);
return 0;
}
Steps to Run:
- Save the program as
multi_args_example.c
. - Compile:
gcc multi_args_example.c -o multi_args_example
- Run the program with multiple arguments:
multi_args_example 1 2 3 4 5
Output:
The sum of the numbers is: 15
Command-line arguments provide flexibility to C programs by allowing users to pass input values directly when executing the program. By using argc
and argv[]
, you can customize how your program behaves based on user input.
At SamagraCS Educational Technology, we believe in practical learning, and command-line arguments are a powerful way to make programs dynamic and interactive. By practicing with the examples provided, you’ll gain confidence in handling user inputs through the command line.
If you have any questions or need further assistance, feel free to reach out to Pawan & Pooja, or the team. Happy coding and keep learning!