Command line arguments let users give information to a program when they start it. This helps the program work differently based on what the user wants.
0
0
Why command line arguments are used
Introduction
When you want to let users choose a file to open without changing the program code.
When you want to set options like 'verbose mode' or 'quiet mode' before the program runs.
When you want to pass numbers or words to the program to process right away.
When you want to run the same program with different inputs quickly from a terminal.
When automating tasks and scripts need to send data to a program.
Syntax
C
int main(int argc, char *argv[]) { // code here return 0; }
argc counts how many arguments are passed, including the program name.
argv is an array of strings holding each argument.
Examples
This prints the program's own name, which is always the first argument.
C
int main(int argc, char *argv[]) { printf("Program name: %s\n", argv[0]); return 0; }
This checks if the user gave an argument and prints it.
C
int main(int argc, char *argv[]) { if (argc > 1) { printf("First argument: %s\n", argv[1]); } else { printf("No arguments given.\n"); } return 0; }
Sample Program
This program prints how many arguments were given and lists each one. The first argument is always the program name.
C
#include <stdio.h> int main(int argc, char *argv[]) { printf("Number of arguments: %d\n", argc); for (int i = 0; i < argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } return 0; }
OutputSuccess
Important Notes
The first argument argv[0] is usually the program's name or path.
Arguments are always strings; you may need to convert them to numbers if needed.
If no extra arguments are given, argc will be 1.
Summary
Command line arguments let users send information to a program when it starts.
They help make programs flexible without changing code.
Arguments are accessed using argc and argv in C.