ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-252 min read

Learn how to parse command line arguments in C using argc and argv. Complete working code for flag parsing, option switches, and type casting.

Understanding argc and argv

Command line arguments allow passing parameters into a C program when it is executed from a terminal shell:

c (ISO Standard)
int main(int argc, char *argv[])
  • argc (argument count): An integer representing the number of command line arguments passed (including the executable name).
  • argv (argument vector): An array of character pointers (strings) representing each argument.

Complete C Implementation

c (ISO Standard)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    printf("Total Arguments (argc): %d\n\n", argc);

    for (int i = 0; i < argc; i++) {
        printf("  argv[%d] = \"%s\"\n", i, argv[i]);
    }

    /* Example: Summing numbers passed via CLI */
    if (argc > 1) {
        int sum = 0;
        printf("\nEvaluating numerical arguments:\n");
        for (int i = 1; i < argc; i++) {
            int val = atoi(argv[i]);
            sum += val;
            printf("    Arg %d -> %d\n", i, val);
        }
        printf("  Total Sum = %d\n", sum);
    }

    return 0;
}

Sample Invocation & Output

Running: ./app 10 25 5

text (ISO Standard)
Total Arguments (argc): 4

  argv[0] = "./app"
  argv[1] = "10"
  argv[2] = "25"
  argv[3] = "5"

Evaluating numerical arguments:
    Arg 1 -> 10
    Arg 2 -> 25
    Arg 3 -> 5
  Total Sum = 40

Complexity Analysis

  • Time Complexity: O(total argument length) linear scan of argument vector strings.
  • Space Complexity: Handled directly by operating system process initialization.

Related C Examples & Tutorials