HOWTO · C++

How to Get Environment Variable in C++

Learn how to read and validate environment variables in C++ with std::getenv

On this page

Use std::getenv from <cstdlib> to look up an environment variable by name. It returns a pointer to the variable’s value when that name is present, or nullptr when it is absent. Check the pointer before using it, copy a value you need to keep into std::string, and validate external values according to your application’s own rules.

Read an environment variable with std::getenv

Include <cstdlib> and pass the expected variable name as a null-terminated string. Environment variable names are not universally required to use uppercase letters. Name matching follows the target platform’s conventions: it is case-sensitive on many POSIX systems, while other platforms may use different rules. Use the exact name expected by the environment where the program runs.

The std::getenv reference documents that the function returns a pointer to the value string, or a null pointer when the name is not found, and that modifying the returned string is undefined behavior. Treat the pointer as read-only. If the value needs to outlive the immediate lookup, copy it into an owned std::string. The following complete example reports whether HOME is available and prints a copy of its value. Its output depends on the environment in which it runs.

Run this example:

#include <cstdlib>
#include <iostream>
#include <string>

int main() {
  const char* raw_home = std::getenv("HOME");
  if (raw_home == nullptr) {
    std::cout << "HOME is not set\n";
    return 0;
  }

  const std::string home(raw_home);
  std::cout << "HOME: " << home << '\n';
  return 0;
}

Handle a missing environment variable safely

Test the result against nullptr before passing it to a string constructor or reading through it. Constructing std::string from a null pointer is not a safe way to represent an absent variable; the constructor requires a valid character sequence. A conditional expression such as raw_value == nullptr ? "fallback" : raw_value can choose a default, but use it only when treating absence as that default matches the application’s behavior.

Do not use std::string::empty() to decide whether a variable exists. A present variable can contain an empty string: std::getenv then returns a non-null pointer whose first character is the terminator. Keep presence and content checks separate. For example, first handle the nullptr case, then copy the value, and only then decide whether an empty value is acceptable. This distinction matters when an unset setting should trigger a default but a deliberately blank setting should be rejected or handled differently.

Validate environment values for your application

Treat environment values as external input. They can be supplied by a shell, service manager, container, or parent process, so validate them against the requirements of the operation that uses them. A path, port number, feature flag, and credential each need different checks. Decide what forms are allowed, what to do when parsing fails, and whether an absent value should select a documented default. Avoid assuming that a generic cleanup step makes arbitrary input safe.

For a narrow policy example, an application that forbids spaces in a particular setting could inspect value.find(' '). The std::string::find member returns the position of the first match, or std::string::npos when no match exists. If a space is found, the application may reject the value or apply a rule defined for that setting. Taking value.substr(0, position) merely truncates at the first space; it does not generally sanitize the value, validate its meaning, or provide a security guarantee. Choose validation that fits the value’s actual use, and report or handle rejected input deliberately.