C Command-line Arguments

Advanced
6 min read
Updated: Nov 2026
1 example

What Is Command-line Arguments?

Declare main as int main(int argc, char *argv[]) to receive arguments. argc is the argument count (at least 1) and argv is an array of strings. argv[0] is usually the program name and argv[argc] is NULL. Convert numbers with strtol or atoi.

Remember
int main(int argc, char *argv[]) {
    /* ./prog 4 6  ->  argc == 3
       argv[0] "./prog"  argv[1] "4"  argv[2] "6" */
}

Cheat Sheet

Keep these facts handy while you work with Command-line Arguments in C.

TopicDetail
argcNumber of arguments including the program name
argv[i]String for argument i
argv[argc]NULL
Convertstrtol, atoi, strtod

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Modular Programming.

Example 1 — Sum the numbers given on the command line

Run as ./sum 4 6 10.

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

int main(int argc, char *argv[]) {
    int sum = 0;

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

How It Works

  1. ./sum 4 6 10 gives argc 4: the program name plus three arguments.
  2. The loop starts at 1 to skip argv[0].
  3. atoi converts each string; 4 + 6 + 10 = 20.

Edge Cases & Pitfalls

Check these before relying on Command-line Arguments in real programs.

argc

Not checking argc

Reading argv[1] with no arguments reads NULL. Check argc first and print usage.

atoi

atoi cannot report errors

Use strtol with an end pointer to detect invalid input.

Key Takeaways

  • argc: count.
  • argv: strings.
  • Validate: before using.

One line: Declare main as int main(int argc, char *argv[]) to receive arguments.

Frequently Asked Questions

It is normally the name used to invoke the program. The standard does not require it to be a full path.
Use strtol or strtod, which report errors, or atoi for quick demos.
Continue with "C Modular Programming" next. Split a program into .c and .h files with clear interfaces. The C Advanced Concepts hub lists every topic in order.

Next: Modular Programming

Split a program into .c and .h files with clear interfaces.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful