Introduction
Imagine you want to run a program that accepts command-line arguments. Let's consider a program like gcc
. To compile an object file named progam
we type the following to the command line:
gcc my_program.c -o my_program
The character my_program.c
,-o
, my_program
are all arguments to the gcc
command. (gcc
is an argument as well, as we shall see)
Command line arguments in C are very useful. They give a function the ability to pass arguments from the command line. All arguments you pass to the command line end up as arguments to the main
function in your program.
Syntax
The main
function that accepts command line arguments is written like this:
#include <stdio.h>
int main(int argc, char argv[])
{
return (0);
}
argc
- Stands for "argument count". It represents the count of arguments supplied to the program.
argv
- Stands for "argument vector". A vector is a one-dimensional array and argv
is a one-dimensional array of strings.
In some functions the argv
is declared like this:
#include <stdio.h>
int main(int argc, char **argv)
{
return (0);
}
The name of an array is converted to the address of its first arguments. Both declarations are similar in this context.
Usage
Let's look at this example:
gcc my_program.c -o my_program
This would result in the following values:
argc: 4
argv[0]: gcc
argv[1]: my_program.c
argv[2]: -o
argv[3]: my_program
As you can see, the first argument (argv[0]
) is the name by which the program was called, in this case gcc
. Thus, there will always be at least one argument to a program, and argc
will always be at least 1.
Example
#include <stdio.h>
/**
* main - Entry point.
* @argc: Argument count
* @argv: Argument vector
*
* Return: 0 (Success)
*/
int main(int argc, char *argv[])
{
printf("Argument count (argc): %d\n", argc);
/*Print each command-line argument */
for (int i = 0; i < argc; i++)
{
printf("Argument %d: %s\n", i, argv[i]);
}
return (0);
}
If you compile and run this program with the command ./program arg1 arg2 arg3
, the output will be:
Argument count (argc): 4
Argument 0: ./program
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
Conclusion
In summary, argc
and argv
are essential for building flexible and versatile C programs that can adapt their behavior based on command-line inputs.
Happy hacking!
Top comments (0)