← Back to C Course | Chapter 12: Advanced Topics | Lesson 5 of 20

C Command Line Arguments

What are Command Line Arguments?

Command line arguments let a user configure a program's behavior at launch time without editing or recompiling the source code, by typing extra words after the program name in the terminal. This is how tools like compilers and file utilities accept filenames, flags, and options.

Example: What are Command Line Arguments?

c
#include <stdio.h>
int main(int argc, char *argv[]) {
	printf("Program received %d arguments", argc);
	return 0;
}

The argc Parameter

argc holds the total count of arguments the program was launched with, and it always includes the program's own name as the first entry, so a program run with two extra words has argc equal to 3, not 2. Checking argc before accessing argv is essential to avoid reading past the arguments that were actually supplied.

Example: The argc Parameter

c
#include <stdio.h>
int main(int argc, char *argv[]) {
	printf("%d", argc);
	return 0;
}

The argv Parameter

argv is an array of C-string pointers holding the actual argument text, where argv[0] is conventionally the program's own invocation name and argv[1] onward are the arguments the user actually typed. Each entry is a plain null-terminated string, so you use standard string functions to parse or compare them.

Example: The argv Parameter

c
#include <stdio.h>
int main(int argc, char *argv[]) {
	printf("%s", argv[0]);
	return 0;
}

Reading Argument Values

To use the arguments passed at launch, index into argv starting from position 1 (skipping the program name at index 0), converting each string to a number with atoi() or similar if the argument represents numeric input rather than text. Process them in the order the user supplied them, since argv preserves that order exactly.

Example: Reading Argument Values

c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
	char *fakeArgv[2] = {"prog", "42"};
	int value = atoi(fakeArgv[1]);
	printf("%d", value);
	return 0;
}

Validating Argument Counts

Because argv is only as long as argc says it is, reading argv[i] for an i that exceeds argc-1 reads unallocated memory and can crash or behave unpredictably. Always compare the expected argument count against argc, and print a usage message rather than proceeding, before touching any index beyond what was actually passed.

Example: Validating Argument Counts

c
#include <stdio.h>
int main(int argc, char *argv[]) {
	if (argc < 2) {
		printf("Not enough arguments");
		return 1;
	}
	printf("%s", argv[1]);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.