The C Language

main and command-line arguments (argc/argv)

When you double-click a program or type its name in a terminal, where does it actually start? Every C program has one designated front door called main — the function the system calls to begin your program. Execution starts at main, and when main returns, the program ends, handing a small number back to whoever launched it as a success-or-failure report.

main comes in two standard forms. The simplest is 'int main(void)', which takes nothing and returns an int exit status (0 conventionally means success, non-zero means some kind of failure). The richer form receives the command-line arguments: 'int main(int argc, char *argv[])'. Here argc (argument count) is how many words were on the command line including the program's own name, and argv (argument vector) is an array of those words as strings. So if you run a program as 'myprog hello 42', then argc is 3, argv[0] is the program name, argv[1] is "hello", and argv[2] is "42" (note: a string, not the number 42 — you must convert it yourself). The return value of main becomes the program's exit status, the same value a shell reads to know whether your program succeeded.

Why this matters: argc and argv are how a program receives input from the person or script that launched it — file names to process, options, flags. This is the foundation of every command-line tool. Two honest details: argv[0] is the program's own name, so real arguments start at index 1; and argv[argc] is guaranteed to be a null pointer, marking the end of the list. Arguments arrive as text strings, so a numeric argument like "42" must be converted with something like atoi() or strtol() before you can do arithmetic on it.

#include <stdio.h> int main(int argc, char *argv[]) { printf("%d arguments\n", argc); for (int i = 0; i < argc; i++) printf("argv[%d] = %s\n", i, argv[i]); return 0; /* 0 = success exit status */ }

Run as ./prog hello 42, this prints argc as 3 and the three argv strings; argv[0] is the program name, and 42 arrives as text.

argv[0] is the program name, so real arguments begin at index 1, and argv[argc] is a null pointer. Arguments are always text — "42" is a string, not the integer 42; convert with atoi or strtol before doing arithmetic.

Also called
the main functionprogram entry point主函式程式進入點