liveBook · Manning

Command-line argument

As explained in Modern C, Third Edition

A command-line argument is a string value supplied to a program when it is invoked from a command-line environment.

A command-line argument is a value supplied when a program is invoked. For a C program, `main` can receive those values through `argc` and `argv`. Each argument arrives as a string, even when the program intends to use it as a number. section 7.2

int main(void);
int main(int argc, char* argv[argc+1]);

The second form of `main` provides `argc` for processing the argument vector `argv`. `argv[0]` points to the program invocation name—usually the executable name—and `argv[argc]` is a null pointer. Use `argc` to determine which argument positions to process. section 7.2

Interpreting a numeric argument

`double const a = strtod(argv[i], nullptr);` decodes a double from an argument string. The command line does not perform that conversion for the program; interpreting the string is the program’s responsibility. section 7.2

TAKEAWAY: Compiler command-line arguments and arguments passed to a running program are different uses of the same idea. For example, `c17 -Wall -o getting-started getting-started.c -lm` invokes a compiler with arguments; `./getting-started` then invokes the resulting program. Compiler names and accepted arguments depend on the platform. section 1.2

A command-line argument is also distinct from a C function-call argument. In `printf(..., i, A[i], A[i]*A[i])`, expressions supply values directly to a function call; `argv` instead holds strings received when the program starts. section 2.4.2 section 7.2

How Modern C, Third Edition covers it

How deep it goes
Defines `argc` and `argv`, identifies their special positions, and shows numeric decoding; leaves compiler translation mechanics aside.
Examples
Uses compiler invocation commands and a `strtod(argv[i], nullptr)` expression.
What it assumes
Assumes familiarity with C program invocation and introduces `argv` as strings before relying on its pointer representation.
What you can do after
Apply it via `argc`, `argv`, and `strtod` to read an argument and interpret it as a double.
How it connects
Connects `main`, strings, pointers, arrays, and `strtod` to command-line input.

Also explained in

Compare how 14 books explain command-line argument →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.