Course contentsShow
← C
Lesson 1208 of 1,21916. Practice and ProjectsFree lesson

Adding command line flags (e.g., `-i` for case)

Adding command line flags (e.g., -i for case)

What you'll learn: How to scan command line arguments to toggle specific behaviors in your utility programs.

Most professional tools allow users to change how the program behaves by passing "flags." For example, grep uses -i to ignore case sensitivity. In C, these flags arrive at your main function through the argv array.

The logic of a flag

Think of a flag like a light switch. At the very start of your program, you define a variable (usually an int acting as a boolean) and set it to 0 (off). Before your program does its primary work, it looks at the "inbox" of arguments provided by the user. If it sees a specific string like "-i", it flips that switch to 1 (on).

Implementing the check

To handle flags, you need to loop through the argv array starting from index 1. We use strcmp from the <string.h> library to check if any argument matches our desired flag.

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

int main(int argc, char *argv[]) {
    int ignoreCase = 0; // The "switch" is off by default

    // Look through all arguments passed by the user
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-i") == 0) {
            ignoreCase = 1; // Flip the switch!
        }
    }

    // Now, use that switch to change behavior
    if (ignoreCase) {
        printf("Search mode: Case-insensitive\n");
    } else {
        printf("Search mode: Standard\n");
    }

    return 0;
}

Why this order matters

In a command-line utility, your program should always process its configuration (the flags) before processing its data (like a filename). By checking argv first, you ensure that by the time you reach the "meat" of your code, your program knows exactly how the user wants it to behave. If you were building a search tool, you would now use that ignoreCase variable to decide whether to convert strings to lowercase before comparing them.

Key takeaway

Flags are simple integer "switches" that you toggle by comparing strings in the argv array during program startup.