C++ getenv()

If the environment variable passed to the getenv() function is not in the environment list, it returns a null pointer.

getenv() prototype

char* getenv( const char* env_var );

This function is defined in <cstdlib> header file.


getenv() Parameters

  • env_var: C string containing the name of the environment variable.

getenv() Return value

The getenv() function returns:

  • The value of the environment variable represented by env_var.
  • If the environment variable is not in the environment list, it returns a null pointer.

Example : How getenv() function works?

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	/* A list of possible environment variables*/
	const char *env_var[5] = {"PUBLIC","HOME","SESSIONNAME","LIB","SystemDrive"};
	char *env_val[5];

	for(int i=0; i<5; i++)
	{
		/* Getting environment value if exists */
		env_val[i] = getenv(env_var[i]);
		if (env_val[i] != NULL)
			cout << "Variable = " << env_var[i] << ", Value= " << env_val[i] << endl;
		else
			cout << env_var[i] << " doesn't exist" << endl;
	}
}

When you run the program, a possible output will be:

Variable = PUBLIC, Value= C:\Users\Public
HOME doesn't exist
Variable = SESSIONNAME, Value= Console
LIB doesn't exist
Variable = SystemDrive, Value= C:

Note: The output differs for different device. In order to see the list of all the environment variables and their values:

For Windows: type set and press enter on command prompt

For Linux: type env and press enter on terminal

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges