How to Get Environment Variable in C++?

Environment variables are globally accessible named values that store information about the system environment where your code is executed. They are also used to store configuration settings, paths to important directories, and other system-specific data as well. In this article, we will learn how to get environment variables in C++.

Accessing Environment Variable in C++

To get the value of an environment variable in C++, we can use the getenv() function provided by the <cstdlib> header. This function takes the name of the environment variable as a parameter and returns its value. Following is the syntax to use the getenv() function:

Syntax

char* getenv(const char* env_name);

where:

  • env_name: is the name of the environment variable you want to get.
  • return value: Char * pointer to the value of the specified environment variable or NULL if the variable is not found.

C++ Program to Get Environment Variable

The below example demonstrates the use of the getenv() function to get the value of an environment variable in C++:

C++
// C++ Program to Get Environment Variable 
#include <cstdlib> 
#include <iostream>
using namespace std;

int main()
{
    // Specify the name of the environment variable
    const char* env_var_name = "PATH";

    // Get the value of the environment variable
    const char* env_var_value = getenv(env_var_name);

    // Check if the environment variable was found
    if (env_var_value != nullptr) {
        cout << env_var_name << " = " << env_var_value<< endl;
    }
    else {
        cout << "Environment variable " << env_var_name<< " not found." << endl;
    }

    return 0;
}

Output
PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Time Complexity: O(1)
Auxiliary Space: O(1)

Note: The value of the output may differ in your system.