basics · beginner · ~15 min

Parse a single `--key=value` flag

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

Challenge

Scan a program's command-line arguments for a --key=value flag and hand back the value — a hand-rolled mini version of getopt_long.

Task

Implement int find_flag(int argc, char **argv, const char *key, const char **out). Scan argv[1] through argv[argc-1] for the first argument that begins with key immediately followed by =. If found, set *out to point at the value (everything after the =, which may be empty) and return 1. If no such argument exists, return 0 and leave *out unchanged.

Input

argc/argv as passed to main, a flag name key such as "--port", and an output pointer out that receives the value on success.

Output

Returns 1 if the flag is present (with *out pointing into argv at the value), otherwise 0.

Example

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

Edge cases

  • An argument equal to key but with no = (e.g. "--port" alone) does not match.
  • An empty value after = is a valid match.
  • If several arguments match, return the first.

Rules

  • No allocations — *out points into argv (valid for the program's lifetime).
  • Use a length-bounded prefix check (strncmp), not strcmp, and verify the = separator.

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 as passed to main, a key string, and an out pointer for the value.

Output format

1 if the flag is found (with *out set to the value), otherwise 0.

Constraints

No allocations; *out is a pointer into argv. Match key followed by '='; take the first match.

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.