Command line arguments let you give information to a program when you start it. This helps the program do different things without changing its code.
0
0
Syntax of command line arguments
Introduction
You want to tell a program which file to open when it starts.
You want to set options or modes for a program without asking inside the program.
You want to pass numbers or words to a program to process right away.
You want to run the same program with different inputs easily from the terminal.
Syntax
C
int main(int argc, char *argv[]) { // Your code here }
argc counts how many arguments are passed, including the program name.
argv is an array of strings holding each argument. argv[0] is the program name.
Examples
This example prints the program name and the first argument if given.
C
int main(int argc, char *argv[]) { printf("Program name: %s\n", argv[0]); if (argc > 1) { printf("First argument: %s\n", argv[1]); } return 0; }
This example prints all arguments passed to the program.
C
int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } return 0; }
Sample Program
This program shows how many arguments were passed and lists each one. The first argument is always the program's name.
C
#include <stdio.h> int main(int argc, char *argv[]) { printf("Total arguments: %d\n", argc); for (int i = 0; i < argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } return 0; }
OutputSuccess
Important Notes
Arguments are always strings. You may need to convert them to numbers if needed.
If no extra arguments are given, argc will be 1, and only argv[0] exists.
Summary
Command line arguments let you pass information to your program when it starts.
argc tells how many arguments there are, including the program name.
argv holds the actual arguments as strings in an array.