C Command-Line Arguments
What are Command-Line Arguments?
You have learned that a function can take parameters, like add(5, 3).
main() is also a function. Command-line arguments are values that you give to main() when you start the program.
You write them after the program name, when you start the program from the command line (also called the terminal):
./add 5 3
This starts a program called add, and gives it two arguments: 5 and 3.
Why Use Command-Line Arguments?
You use them all the time, without knowing it!
When you double-click a file, like photo.jpg, your computer starts the photo program and gives it the file name as a command-line argument. That is how the program knows which photo to open.
Your own programs can work the same way. With command-line arguments, a program gets what it needs when it starts, so it does not have to stop and ask the user, like it does with scanf().
Read the Arguments in main()
To read the arguments, write main() with two parameters:
int main(int argc, char *argv[])
argc(argument count) is the number of arguments. The program name counts too.argv(argument vector, which means a list of arguments) holds the arguments as strings, like an array of strings.argv[0]is the program name.
When you start the program with ./add 5 3, they look like this:
argc is 3, because the program name counts too.Example: Say Hello
This program says hello to the name you write after the program name:
Example
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Please write your name after the program name\n");
return 1;
}
printf("Hello %s\n", argv[1]);
return 0;
}
Compile the program, and start it with your name:
gcc hello.c -o hello
./hello Liam
Result:
Hello Liam
The if statement checks that a name was given. If you only type ./hello, argc is 1 and argv[1] does not exist, so the program prints a message instead.
Note: On Windows, type hello Liam instead of ./hello Liam.
Arguments Are Strings
All arguments are strings, even when you type a number. To use an argument as a number, convert it with the atoi() function from <stdlib.h>.
Here is the add program from the start of this chapter:
Example
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Please write two numbers after the program name\n");
return 1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("%d + %d = %d\n", a, b, a + b);
return 0;
}
Compile the program, and start it with two numbers:
gcc add.c -o add
./add 5 3
Result:
5 + 3 = 8
This time, argc must be 3: the program name and two numbers.
Run It in Code::Blocks
You do not need the command line to try this. In Code::Blocks, go to Project > Set programs' arguments, write the arguments (like 5 3), and run the program as usual.
Note: The "Try it Yourself" editor on this website cannot give arguments to a program. That is why the examples on this page do not have a "Try it Yourself" button.