Learn C
#include "stdlib/getopt.h"

Parsing Options with getopt in C

#concept

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.

#how it works
1

Option string declares

"ab:" means -a flag plus -b requiring an argument (the colon) — the whole interface in three characters.

2

Loop to exhaustion

while ((c = getopt(argc, argv, "ab:")) != -1) switch (c) — each iteration handles one flag, -1 ends options.

3

optarg carries values

case 'b': value = optarg; — the flag's argument arrives as a string for conversion and validation.

4

optind resumes positionals

After -1, argv[optind..] holds remaining positional arguments — options first, files after, conventionally.

#example
#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;
}
Output
verbose=1
1The option string "v" declares a single flag with no argument.
2Run as prog -v, the loop sees 'v' once and sets verbose before -1 ends parsing.
3verbose=1 prints — flag parsed, clustered and ordered forms handled for free.
#use cases
Unix-conventional CLIs (-v, -o file, -- terminators)
Replacing hand-rolled argv loops before they rot
Required option arguments via colon declarations plus optarg
Long options through getopt_long with identical structure

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.