Table of contents
1.
Introduction
2.
What are command line arguments in C?
3.
Syntax of Command Line Arguments in C
3.1.
C
4.
Example
4.1.
C
5.
Properties of Command Line Arguments in C
5.1.
C
6.
Output in Different Scenarios: Command Line Arguments in C
6.1.
Without Argument
6.2.
C
6.3.
Three Arguments
6.4.
C
6.5.
Single Argument Containing Spaces
6.6.
C
6.7.
Terminal Input in C
6.8.
C
7.
Frequently Asked Questions
7.1.
What is argv and argc in C?
7.2.
What are command line arguments using function?
7.3.
What happens if I exceed the expected number of arguments?
7.4.
Can command line arguments be used for user authentication purposes?
8.
Conclusion
Last Updated: Nov 5, 2024
Easy

Command Line Arguments in C

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Command line arguments in C are a powerful feature that allows users to pass input directly to a program when executing it from a terminal or command prompt. This capability enhances the flexibility and functionality of applications by enabling users to customize program behavior without modifying the code.

Command Line Arguments in C

In this article, we will learn what command line arguments are, how they are structured in C, and the ways they can be used to enhance program capabilities. 

What are command line arguments in C?

Command line arguments in C are a method for passing information to a program at the time of execution via the command line interface. This allows users to provide inputs directly when running the program, enabling more dynamic and flexible behavior without hardcoding values in the code.

In C, command line arguments are typically accessed through the main function, which can be defined with two parameters: int argc and char *argv[].

Syntax of Command Line Arguments in C

In C programming, the syntax for handling command line arguments involves two main components in the main function declaration: int argc and char *argv[]. Here’s how they work:

  • int argc: This stands for "argument count". It represents the number of arguments passed to the program from the command line, including the name of the program itself. Therefore, the minimum value of argc is 1.
     
  • char *argv[]: This is an array of character strings (or an array of pointers to strings) representing the arguments passed to the program. argv[0] is always the name of the program as it was invoked, and argv[1] is the first command line argument, with subsequent indexes storing additional arguments.

Here’s a basic example to illustrate:

  • C

C

#include <stdio.h>
int main(int argc, char *argv[]) {
   printf("Program name: %s\n", argv[0]);
   if (argc > 1) {
       printf("The first argument is: %s\n", argv[1]);
   }
   return 0;
}
You can also try this code with Online C Compiler
Run Code


In this code:

  • argv[0] will display the program's name.
     
  • argv[1] will display the first command line argument, if one is provided.

Example

To better understand how command line arguments can be utilized in C, let's walk through an example. This example will demonstrate how to read and display command line arguments that are input through the terminal.

  • C

C

#include <stdio.h>

int main(int argc, char *argv[]) {

   int i;

   printf("Number of arguments: %d\n", argc);

   for (i = 0; i < argc; i++) {

       printf("Argument %d: %s\n", i, argv[i]);

   }

   return 0;

}
You can also try this code with Online C Compiler
Run Code

In this program:

  • The for loop iterates over each command line argument.
     
  • argc counts how many arguments there are.
     
  • argv contains each argument as a string.

To run this program, you would compile it first and then execute it from the terminal, providing any arguments you wish to pass. For example, if your compiled program is named example, you could run:

./example Hello World!


This would output:

Number of arguments: 3
Argument 0: ./example
Argument 1: Hello
Argument 2: World!

Properties of Command Line Arguments in C

Command line arguments in C provide several properties that make them particularly useful for creating flexible and dynamic programs. Here are some key properties:

  • Flexibility: You can pass any number of arguments to a program at runtime without modifying the source code. This allows users to specify different behaviors or inputs each time they run the program.
     
  • Zero-indexed: The argv array is zero-indexed with argv[0] typically holding the name of the executable and subsequent indices holding the actual arguments passed by the user.
     
  • Type: All command line arguments are passed as strings (character arrays). If your program needs other types (like integers or floats), you need to convert these strings into the respective types using functions like atoi() or atof().
     
  • Global accessibility: Once passed into the main function, these arguments can be accessed from any part of the program, making them globally available.
     
  • Memory management: The memory for storing these arguments is managed by the operating system. The programmer does not need to allocate memory explicitly, but care should be taken not to modify the contents of argv directly in most cases, as this can lead to unpredictable behavior.
     

Here is a simple example to illustrate the conversion of command line arguments from strings to integers:

  • C

C

#include <stdio.h>
#include <stdlib.h> // For atoi()

int main(int argc, char *argv[]) {
   if (argc > 1) {
       int number = atoi(argv[1]); // Converts the first argument to an integer
       printf("The first argument converted to integer is: %d\n", number);
   } else {
       printf("No arguments were provided.\n");
   }
   return 0;
}
You can also try this code with Online C Compiler
Run Code


In this example:

  • The atoi() function is used to convert the first command line argument from a string to an integer.
     
  • This conversion is crucial for programs that require numerical input from the user.

Output in Different Scenarios: Command Line Arguments in C

Handling different scenarios with command line arguments can drastically change how a C program behaves. By understanding and anticipating these different cases, you can ensure that your program functions reliably under various conditions.

Let's discuss how a simple C program might handle three specific scenarios: no arguments, three arguments, and a single argument containing spaces.

Without Argument

When no arguments are passed to the program, argc will be 1, and argv[0] will contain the name of the executable. Here's how you can handle this scenario:

  • C

C

#include <stdio.h>
int main(int argc, char *argv[]) {
   if (argc == 1) {
       printf("No additional command line arguments were provided.\n");
   }
   return 0;
}
You can also try this code with Online C Compiler
Run Code


This code checks if argc equals 1 and informs the user that no additional arguments were provided.

Three Arguments

When three arguments are passed, argc will be 4 (including the program name), and you can access each argument using argv:

  • C

C

#include <stdio.h>
int main(int argc, char *argv[]) {
   if (argc == 4) {
       printf("Three arguments provided:\n");
       for (int i = 1; i < argc; i++) {
           printf("Argument %d: %s\n", i, argv[i]);
       }
   }
   return 0;
}
You can also try this code with Online C Compiler
Run Code


This program will print each of the three arguments provided by the user.

Single Argument Containing Spaces

If you pass a single argument that includes spaces, it should be enclosed in quotes to ensure it is treated as one argument. For example, running ./program "Hello World" would give you:

  • C

C

#include <stdio.h>
int main(int argc, char *argv[]) {
   if (argc == 2) {
       printf("Single argument provided: %s\n", argv[1]);
   }
   return 0;
}
You can also try this code with Online C Compiler
Run Code


This code will display the entire string "Hello World" as a single argument.

Terminal Input in C

To make C programs interactive and user-friendly, handling terminal input is crucial. This enables programs to accept user input directly from the command line, affecting the program's behavior in real-time based on user needs. Here’s how you can manage terminal input in your C programs:

When a C program is run from a terminal, it can accept input parameters immediately following the command to execute the program. This is particularly useful for scripts and utilities that require user customization without changing the program's source code.

  • C

C

#include <stdio.h>

int main() {

   char input[100]; // Declare a char array to hold the input

   printf("Enter a string: ");

   fgets(input, sizeof(input), stdin); // Read string from user

   printf("You entered: %s", input);

   return 0;

}
You can also try this code with Online C Compiler
Run Code

Output

Enter a string: Hello
You entered: Hello


In this program:

  • The fgets function is used to read a line of text from the terminal, which allows for spaces in the input.
     
  • The input is then echoed back to the user with printf.
     
  • This simple method of capturing terminal input makes your C programs interactive by allowing them to respond to user input dynamically.

Frequently Asked Questions

What is argv and argc in C?

argc is the count of command line arguments, while argv is an array of strings representing those arguments passed to the program.

What are command line arguments using function?

Command line arguments allow users to pass input values to a program during execution, facilitating dynamic behavior and customization through the main function parameters.

What happens if I exceed the expected number of arguments?

If more arguments are provided than expected, the extra arguments will simply be ignored unless the program is specifically designed to handle them. It’s important to design your program to manage or warn about unexpected arguments to prevent potential errors or confusion.

Can command line arguments be used for user authentication purposes?

Yes, but with caution. You can pass usernames or authentication tokens as arguments, but for security reasons, sensitive information should not be passed directly through the terminal as it can be accessed via command history or process lists by other users on the same machine.

Conclusion

In this article, we have learned about the essentials of using command line arguments in C programming. Starting from the basic syntax involving argc and argv, we learned how these arguments allow programs to handle user inputs dynamically, enhancing the flexibility and usability of C programs. We looked into examples to show how to process input from the terminal, handle various input scenarios, and discussed the properties that make command line arguments a powerful tool for programmers.

You can refer to our guided paths on the Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass