Back to C Programming
2026-07-155 min read

Command Line Arguments in C

Learn Command Line Arguments in C step by step with clear examples and exercises.

Why This Matters

Command Line Arguments in C are an essential aspect of programming that allows for greater flexibility and customization of applications. By understanding how to handle command line arguments, you can create more powerful and user-friendly programs. Additionally, this skill is valuable for debugging real-world issues and preparing for job interviews.

Prerequisites

Before diving into Command Line Arguments in C, it's essential to have a solid grasp of the following topics:

  1. Basic C syntax (variables, operators, control structures)
  2. Functions in C
  3. File I/O (input and output)
  4. Understanding pointers and arrays in C
  5. Data types and their conversions

Core Concept

Command Line Arguments are values passed to a program from the command line when it is executed. The main function of a C program receives these arguments as an array named argv (argument vector) and a count of the arguments stored in the variable argc (argument count).

#include <stdio.h>

int main(int argc, char *argv[]) {
// Your code here
}

In this example, main() accepts two parameters: argc and argv. argc is the number of arguments passed to the program, while argv is an array containing those arguments as strings. The first argument (index 0) is always the name of the executable itself.

Accessing Command Line Arguments

To access individual command line arguments, you can use a loop and index into the argv array:

for (int i = 1; i < argc; ++i) {
printf("Argument %d: %s\n", i, argv[i]);
}

Parsing Command Line Arguments

When working with command line arguments, it's common to convert string arguments to other data types. For example, you can use the atoi() function to convert a string argument to an integer:

int num = atoi(argv[1]);

However, be aware that using atoi() can lead to issues with large numbers or invalid input. To handle these cases, you may want to implement error checking and validation in your program.

Worked Example

Let's create a simple C program that accepts two command line arguments, calculates their sum, and checks for valid input:

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

int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s number1 number2\n", argv[0]);
return 1;
}

// Validate input and convert to integers
int num1 = -1;
int num2 = -1;
char *endptr;

errno = 0;
num1 = strtol(argv[1], &endptr, 10);
if (errno == ERANGE || (num1 == LONG_MIN && *endptr != '\0') || *endptr != argv[1][argc - 1]) {
printf("Invalid number: %s\n", argv[1]);
return 1;
}

errno = 0;
num2 = strtol(argv[2], &endptr, 10);
if (errno == ERANGE || (num2 == LONG_MIN && *endptr != '\0') || *endptr != argv[2][argc - 1]) {
printf("Invalid number: %s\n", argv[2]);
return 1;
}

int sum = num1 + num2;
printf("The sum of %d and %d is: %d\n", num1, num2, sum);
return 0;
}

This example demonstrates how to validate command line arguments for validity before processing them. It uses the strtol() function from the standard library to convert string arguments to integers and checks for errors during conversion.

Common Mistakes

  1. Forgetting to check argc: Always ensure that the number of arguments passed matches the expected number in your program.
  2. Not handling invalid input: If the user provides an incorrect number of arguments or non-numeric input, your program should handle these cases gracefully.
  3. Incorrectly parsing command line arguments: Use atoi() to convert string arguments to integers, but be aware that it can cause issues with large numbers or invalid input. Consider using strtol() for more robust error handling.
  4. Ignoring the first argument (argv[0]): This is the name of the executable itself and should not be used as a regular argument unless you specifically want to access the program's name at runtime.
  5. Not properly freeing memory: If you dynamically allocate memory in your command line argument processing, ensure that you free it when the program exits or no longer needs it.
  6. Not considering edge cases: Be mindful of unusual input scenarios (e.g., negative numbers, floating-point numbers, or non-numeric input) and handle them appropriately within your program.

Practice Questions

  1. Write a C program that accepts three command line arguments and calculates their average.
  2. Create a program that takes a filename as an argument, reads the contents of the file, and prints the total number of words in it.
  3. Develop a simple calculator that performs addition, subtraction, multiplication, and division based on command line arguments.
  4. Write a program that accepts a command line argument specifying a directory path and recursively lists all files within that directory and its subdirectories.
  5. Create a program that takes command line arguments to sort a list of integers in ascending or descending order, depending on the provided flag (e.g., -a for ascending, -d for descending).

FAQ

  1. Why is argc always one more than the number of user-provided arguments?

The first argument (argv[0]) is the name of the executable itself, which is not provided by the user but by the operating system.

  1. How can I handle invalid input when parsing command line arguments?

You can use a loop to iterate through the arguments and check each one for validity before processing it in your program. Consider using strtol() or other functions from the standard library for more robust error handling.

  1. What's the best way to parse complex command line arguments with multiple options (e.g., -f, --flag)?

For handling more complex command line arguments, consider using a library like getopt or writing your own argument parsing function that can handle long and short flags, as well as optional arguments.

  1. How do I pass an array as a command line argument?

To pass an array as a command line argument in C, you should convert the array to a string (e.g., using printf or a loop) and then pass that string as a single argument. In your program, you can parse the string into individual elements of the array.

  1. Why is it important to check for errors when parsing command line arguments?

Checking for errors during command line argument parsing ensures that your program handles unexpected input gracefully and avoids potential crashes or incorrect behavior due to invalid data.