getopt
Standard option parsing.
getopt is a free C Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is getopt?
getopt is a POSIX function that parses single-character options for you, following standard Unix conventions.
It lives in <unistd.h> and removes most of the boilerplate of manual flag parsing.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "v")) != -1) {
if (opt == 'v') printf("verbose on\n");
}
return 0;
}The optstring
The third argument to getopt is the optstring: a list of valid option letters.
"abc" means -a, -b, and -c are all accepted boolean flags.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "abc")) != -1) {
printf("saw option -%c\n", opt);
}
return 0;
}The parsing loop
getopt returns the next option character each call, or -1 when finished.
The standard pattern is a while loop with a switch inside to dispatch on the returned character.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "xy")) != -1) {
switch (opt) {
case 'x': printf("x set\n"); break;
case 'y': printf("y set\n"); break;
}
}
return 0;
}Options with arguments
Put a colon after a letter in the optstring to say it takes a value. "o:" means -o requires an argument.
The value becomes available in the global variable optarg.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "o:")) != -1) {
if (opt == 'o') printf("output = %s\n", optarg);
}
return 0;
}Combining flags and value options
You can mix boolean and value-taking options in one optstring. Here -v is a flag and -n takes a number.
getopt also lets users bundle flags, like -vn 5.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt, verbose = 0, n = 0;
while ((opt = getopt(argc, argv, "vn:")) != -1) {
if (opt == 'v') verbose = 1;
else if (opt == 'n') n = atoi(optarg);
}
printf("verbose=%d n=%d\n", verbose, n);
return 0;
}Handling unknown options
When getopt meets an option not in the optstring, it returns '?' and prints an error (unless you silence it).
Add a case '?' to handle bad input gracefully.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "a")) != -1) {
switch (opt) {
case 'a': printf("a\n"); break;
case '?': printf("unknown option\n"); break;
}
}
return 0;
}Missing required arguments
If a value-taking option is given without its value, getopt's behavior depends on the optstring.
Starting the optstring with a colon (":o:") makes getopt return ':' for a missing argument, so you can report it precisely.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, ":f:")) != -1) {
if (opt == 'f') printf("file=%s\n", optarg);
else if (opt == ':') printf("option needs a value\n");
}
return 0;
}optind: where parsing stopped
After the loop, the global optind holds the index in argv of the first non-option argument.
Use it to process remaining positional arguments such as filenames.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "v")) != -1) { }
for (int i = optind; i < argc; i++)
printf("positional: %s\n", argv[i]);
return 0;
}Silencing getopt's messages
By default getopt prints its own error messages to stderr. Set the global opterr to 0 to suppress them and handle errors yourself.
#include <stdio.h>
#include <unistd.h>
extern int opterr;
int main(int argc, char *argv[]) {
opterr = 0;
int opt;
while ((opt = getopt(argc, argv, "a")) != -1) {
if (opt == '?') printf("bad option, handled quietly\n");
}
return 0;
}Identifying the bad option
When getopt returns '?', the global optopt contains the offending option character.
This lets you print a helpful message naming exactly which flag was wrong.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "a")) != -1) {
if (opt == '?')
printf("Unrecognized option: -%c\n", optopt);
}
return 0;
}Long options note
Plain getopt only supports single-letter options. For long options like --verbose, GNU systems provide getopt_long in <getopt.h>.
It uses the same loop but adds a table of long option descriptors.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
printf("getopt parses %d short options\n", argc > 1 ? argc - 1 : 0);
return 0;
}Quick Check
Test your understanding of getopt's optstring syntax.
Recap
You learned standard option parsing with getopt:
- Loop while
getopt(argc, argv, optstring)is not-1, dispatch with aswitch. - A colon after a letter means it takes a value, found in
optarg. optindpoints to the first positional argument afterward.- Globals
opterr,optopt, and a leading colon control error handling.
Frequently asked questions
Is the “getopt” lesson free?
Yes — the full text of “getopt” is free to read here on the web, and the C Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C Academy course, upgrade to CoddyKit PRO.
What will I learn in “getopt”?
Standard option parsing. You practise C Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C Academy?
No prior experience is required. C Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “getopt” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C Academy lesson?
Yes. Every C Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.