Arguments, conversion, and the environment
Check argc and argv bounds, validate numeric text with strtol, and treat environment strings as borrowed external input.
In this chapter7 sections
A program can receive information when it starts, before asking for input. Command-line arguments arrive as strings, so a number-looking argument still needs parsing and validation. The environment supplies other information under separate rules.
1. Understand the hosted main interface
The portable hosted forms include int main(void) and int main(int argc, char *argv[]), or equivalent forms. In a parameter declaration, char *argv[] adjusts to char **argv. Other implementation-defined startup forms may exist; a third environment parameter is not a universally portable standard form. Freestanding startup has different rules.
| Expression | Guarantee or condition |
|---|---|
argc | Nonnegative; zero is permitted. |
argv[argc] | A null pointer sentinel, not an empty string. |
argv[0] | Only when argc > 0: a program-name string, possibly empty when the name is unavailable. |
argv[1] | A usable argument string only after checking argc > 1. |
argv[i] for valid i | Points to a null-terminated argument string; the null pointer sentinel has no string contents. |
2. Check the count before using an argument
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc > 1) {
printf("first=%s\n", argv[1]);
} else {
puts("no input argument");
}
return 0;
}
The format string is fixed and the argument is passed to %s; argument text is not used as a printf format. If there is no input argument, the program takes the alternative path without reading argv[1]. A real command-line interface should also specify whether extra arguments are allowed. The next example requires exactly one.
Under the hosted rules, the argument strings are modifiable and retain their last-stored values through program termination. They are distinct from the borrowed, nonmodifiable storage returned by getenv. A shell, launcher, or operating system decides how typed text becomes argument strings. Quotes, wildcards, and escape characters are not parsed by C’s main interface. In many shells, quoting a phrase sends one string containing a space; the quotation marks themselves are usually removed by the shell. Those details belong to that launcher’s rules, not to portable C.
3. Numeric text needs conversion and validation
argv[1] containing "12" is not already the integer twelve. atoi is convenient but cannot report conversion errors reliably and has undefined behavior when the converted result cannot be represented. strtol exposes where conversion stopped and reports range failure through errno. This example accepts decimal values from one through one hundred, optional leading whitespace and sign, and no trailing characters.
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static bool parse_count(const char *text, long *result)
{
if (text == NULL || result == NULL) return false;
char *end = NULL;
errno = 0;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0' || errno == ERANGE) return false;
if (value < 1 || value > 100) return false;
*result = value;
return true;
}
int main(int argc, char *argv[])
{
long count = 0;
if (argc != 2 || !parse_count(argv[1], &count)) {
fputs("Provide one count from 1 through 100.\n", stderr);
return EXIT_FAILURE;
}
printf("count=%ld\n", count);
return EXIT_SUCCESS;
}
Short-circuit || avoids evaluating argv[1] unless argc == 2. Inside the helper, end == text means no conversion; *end != '\0' rejects leftover text; and ERANGE rejects results outside long’s range. The final range check enforces the application’s smaller domain. Only after every check does the helper write the result.
An empty string, 12tail, a trailing space, a huge number, zero, and 101 are rejected. Leading whitespace and +12 are accepted by the stated contract; if a format requires digits only, add an explicit lexical check rather than silently assuming strtol enforces that format. EXIT_SUCCESS and EXIT_FAILURE communicate completion status to the host; their exact external representation is implementation-defined.
4. Environment strings are borrowed configuration
const char *setting = getenv("CODEDILE_THEME");
const char *theme = setting == NULL ? "default" : setting;
Include <stdlib.h> for getenv and NULL. The lookup returns a string pointer or a null pointer if the variable is absent; an existing empty value is different from absence. The program must not modify or free the returned string. A later getenv call may overwrite the pointed-to string. Copy needed contents into program-owned storage when independent lifetime is required, checking size and allocation failure as appropriate.
Neither arguments nor environment values are automatically trustworthy. Treat them as external input with explicit accepted values. Standard C provides getenv for lookup, but does not provide a universal setenv function or universal shell syntax for creating variables. Platform extensions need their own portability and concurrency rules.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 5.1.2.2.1, 5.1.2.2.3, 6.7.6.3p7, 7.22.1, 7.22.1.4, 7.22.4, 7.22.4.6. Stable core rules used for the C17 baseline; not the final ISO publication.
Before you move on
- Command-line arguments are strings supplied through the hosted startup interface.
- Parsing a number and accepting an application value are separate checks.
- Borrowed environment strings have availability and invalidation rules.
Keep these ideas separate
- Numeric-looking text / Valid number
- A partial conversion, overflow, unwanted sign, or out-of-domain value can make apparently numeric input unacceptable.
Which checks would you use before accepting one command-line argument as a level from zero through 100?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Yes, argv converts numeric-looking text automatically.
argv supplies strings; it does not perform numeric validation.
- No. Parse it and check the accepted syntax and range.
✓ Correct reasoning. Presence, conversion success, and acceptable value range are separate checks.
- Yes, argc records the numeric value of every argument.
argc counts arguments; it does not describe their numeric contents.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. The expanded explanation is above; documented corrections are recorded in the source review.
In a hosted program, argc is nonnegative; zero is permitted. argv[argc] is a null pointer. Only if argc > 0 does argv[0] point to a program-name string; it may be empty if the name is unavailable. Read argv[1] only after checking argc > 1. getenv("VAR_NAME") from <stdlib.h> returns a pointer to an environment string, or NULL if absent. Do not modify or free that returned string; copy it when independent storage is needed.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.