basics · beginner · ~15 min
Walk argv defensively and parse a `key=value` syntax.
Implement int find_flag(int argc, char **argv, const char *key, const char **out).
key is e.g. "--port". The function scans argv[1..] looking for an argument that starts with key=. If found, sets *out to point at the value (the part after =) and returns 1. If not found, returns 0.
argv = {"prog", "--port=8080", "--debug"}
find_flag(3, argv, "--port", &out) -> 1, *out = "8080"
find_flag(3, argv, "--foo", &out) -> 0
Almost every CLI tool you'll write or audit takes flags. Doing a tiny parser by hand teaches you exactly what getopt_long does for free.
argc/argv and key string.
0/1 + pointer-to-value.
No allocations; out is a pointer into argv.
int find_flag(int argc, char **argv, const char *key, const char **out) { /* TODO */ return 0; }
Using strcmp to test prefix — only matches the whole arg. Use strncmp with key length, then verify = follows.
No matching flag; argv[i] equal to key without =; multiple matches (take first).
O(argc * keylen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.