liveBook · Manning

Environment variable

As explained in Modern C, Third Edition

An environment variable is a named string setting provided through a program's runtime environment.

An environment variable is a name–value pair of strings supplied through a program’s runtime environment. A C program can inspect this environment list to receive operating-system-dependent settings such as HOME, PATH, LANG, or LC_ALL. section 8.7

void printenv(char const name[static 1]) {
  if (getenv(name)) {
    char value[256] = { };
    if (getenv_s(nullptr, value, sizeof value, name)) {
      fprintf(stderr,
              "%s: value is longer than %zu\n",
              name, sizeof value);
    } else {
      printf("%s=%s\n", name, value);
    }
  } else {
    fprintf(stderr, "%s not in environment\n", name);
  }
}

This helper checks whether a name exists, copies its value into a fixed-size buffer with getenv_s, and reports when the value does not fit. section 8.7

Safe access follows these rules:

  • Use getenv to test whether a name is present, then use getenv_s to copy its value into a destination buffer. section 8.7
  • Pass nullptr as getenv_s’s first argument when only the copied value is needed; the destination is written only when the result fits. section 8.7
  • Treat available names as operating-system-dependent rather than universally portable. section 8.7

Printing a setting

A printenv helper can report whether HOME exists, print HOME=value when its value fits a 256-character buffer, and otherwise report that the value is longer than the buffer. section 8.7

How Modern C, Third Edition covers it

How deep it goes
Explains name lookup, bounded copying, buffer-fit checks, and length reporting, while deferring dynamic allocation.
Examples
Uses HOME, PATH, LANG, LC_ALL, and a printenv helper as concrete settings and access examples.
What it assumes
Assumes familiarity with C strings, character arrays, pointers, and C library function interfaces.
What you can do after
Operate getenv and getenv_s to detect settings and retrieve values without overflowing a fixed destination buffer.
How it connects
Connects environment variables with the runtime environment, getenv, getenv_s, and locale settings.

Also explained in

Compare how 19 books explain environment variable →

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.