basics · beginner · ~15 min

Parse a single `--key=value` flag

Walk argv defensively and parse a `key=value` syntax.

Challenge

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.

Examples

argv = {"prog", "--port=8080", "--debug"}
find_flag(3, argv, "--port", &out)   -> 1, *out = "8080"
find_flag(3, argv, "--foo",  &out)   -> 0

Why this matters

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.

Input format

argc/argv and key string.

Output format

0/1 + pointer-to-value.

Constraints

No allocations; out is a pointer into argv.

Starter code

int find_flag(int argc, char **argv, const char *key, const char **out) { /* TODO */ return 0; }

Common mistakes

Using strcmp to test prefix — only matches the whole arg. Use strncmp with key length, then verify = follows.

Edge cases to handle

No matching flag; argv[i] equal to key without =; multiple matches (take first).

Complexity

O(argc * keylen).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.