VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-get-environment-variable-in-c/

⇱ How to Get Environment Variable in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Get Environment Variable in C++?

Last Updated : 23 Jul, 2025

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++:


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.

Comment