Parsing Options with getopt in C
POSIX getopt (in <unistd.h>) parses short options systematically: getopt(argc, argv, "ab:") loops returning each flag, with required arguments delivered via optarg and leftovers counted in optind. -a toggles, -b value consumes — clustered flags (-ab), -- end-of-options, and ? error returns handled uniformly.
Hand-rolled argv loops rot into edge-case soup (combined flags, missing values, -- handling); getopt encodes decades of CLI convention once. Long options (--verbose) come from getopt_long with the same loop shape.
Option string declares
"ab:" means -a flag plus -b requiring an argument (the colon) — the whole interface in three characters.
Loop to exhaustion
while ((c = getopt(argc, argv, "ab:")) != -1) switch (c) — each iteration handles one flag, -1 ends options.
optarg carries values
case 'b': value = optarg; — the flag's argument arrives as a string for conversion and validation.
optind resumes positionals
After -1, argv[optind..] holds remaining positional arguments — options first, files after, conventionally.
#include <stdio.h>#include <unistd.h> int main(int argc, char *argv[]) { int verbose = 0; int c; while ((c = getopt(argc, argv, "v")) != -1) { if (c == 'v') verbose = 1; } printf("verbose=%d\n", verbose); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.