C Academy · Lesson

Parsing Options

Handle flags.

Lesson 2 of 413 steps

Parsing Options is a free C Academy lesson on CoddyKit. This is lesson 2 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, and your progress syncs across the web and the CoddyKit app. The C Academy course includes 4 lessons in total.

Options vs positional arguments

Command-line arguments come in two flavors. Positional arguments are values like filenames. Options (also called flags) start with a dash, like -v or --help.

This lesson shows how to detect and handle flags manually.

#include <stdio.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        if (argv[i][0] == '-')
            printf("option: %s\n", argv[i]);
        else
            printf("value:  %s\n", argv[i]);
    }
    return 0;
}

Detecting a flag

To check for a specific flag, compare each argument with strcmp.

Here we set a boolean when we see -v for verbose mode.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int verbose = 0;
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0)
            verbose = 1;
    }
    printf("verbose = %d\n", verbose);
    return 0;
}

Supporting long options

Many tools accept both a short form (-h) and a long form (--help).

Check for either spelling with two comparisons joined by ||.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-h") == 0 ||
            strcmp(argv[i], "--help") == 0) {
            printf("Usage: prog [options]\n");
            return 0;
        }
    }
    printf("No help requested\n");
    return 0;
}

Options that take a value

Some flags need an argument, like -o output.txt. When you see such a flag, the next element of argv is its value.

Advance the loop index and check you did not run past the end.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    const char *output = "default.txt";
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-o") == 0 && i + 1 < argc) {
            output = argv[++i];
        }
    }
    printf("Output file: %s\n", output);
    return 0;
}

Handle the missing value

If -o is the last argument, there is no value after it. Reading argv[i+1] would be out of bounds.

Always test i + 1 < argc before consuming the next token, and report an error otherwise.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-n") == 0) {
            if (i + 1 >= argc) {
                printf("Error: -n needs a value\n");
                return 1;
            }
            printf("n = %s\n", argv[++i]);
        }
    }
    return 0;
}

Combining boolean flags and values

A realistic parser tracks several flags at once: some boolean, some with values. Use separate variables for each setting.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int verbose = 0;
    const char *name = "world";
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0) verbose = 1;
        else if (strcmp(argv[i], "-name") == 0 && i+1 < argc) name = argv[++i];
    }
    if (verbose) printf("verbose mode\n");
    printf("Hello, %s\n", name);
    return 0;
}

Recognizing the end of options

By convention, a lone -- marks the end of options. Everything after it is treated as a positional argument, even if it starts with a dash.

This lets users pass filenames that begin with -.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int opts_done = 0;
    for (int i = 1; i < argc; i++) {
        if (!opts_done && strcmp(argv[i], "--") == 0) {
            opts_done = 1;
            continue;
        }
        printf("%s: %s\n", opts_done ? "value" : "token", argv[i]);
    }
    return 0;
}

Collecting positional arguments

Often you want flags plus a list of files. Skip the recognized options and store the rest as positional arguments.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        if (argv[i][0] == '-') continue;
        printf("file: %s\n", argv[i]);
    }
    return 0;
}

Unknown option handling

A friendly tool reports unknown flags instead of silently ignoring them. Check against your known options and warn otherwise.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
        if (argv[i][0] != '-') continue;
        if (strcmp(argv[i], "-v") != 0)
            printf("Unknown option: %s\n", argv[i]);
    }
    return 0;
}

Converting option values

Option values arrive as strings. Convert numeric ones with strtol, which also reports parse errors via an end pointer.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int count = 1;
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-c") == 0 && i+1 < argc)
            count = (int) strtol(argv[++i], NULL, 10);
    }
    printf("count = %d\n", count);
    return 0;
}

Why a real parser helps

Manual parsing works but grows messy with combined short flags (-vf), = syntax (--name=foo), and ordering rules.

The standard getopt function, covered next, handles these conventions for you.

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Parsed %d tokens manually\n", argc - 1);
    return 0;
}

Quick Check

Test your understanding of option parsing pitfalls.

Recap

You learned manual option parsing:

  • Flags start with -; compare them with strcmp.
  • Support short and long forms with ||.
  • Value-taking options consume the next token — guard with i + 1 < argc.
  • -- ends option parsing; report unknown flags; convert numeric values with strtol.
Free to start

Learn C with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
39
Lessons
144

Frequently Asked Questions

Is the “Parsing Options” lesson free?

Yes — the full text of “Parsing Options” is free to read here on the web. 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. The C Academy course includes 4 lessons in total.

What will I learn in “Parsing Options”?

Handle flags. 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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Parsing Options” 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.

All lessons in this course

  1. argc and argv
  2. Parsing Options
  3. getopt
  4. Building a CLI Tool
← Back to C Academy