gtpc2m9aC/C++ Language Support User's Guide

unsetenv-Delete an Environment Variable

This function deletes environment variables.

Format

#define _POSIX_SOURCE
#include <stdlib.h>
int unsetenv(const char *var_name);

var_name
A pointer to a character string that contains the name of the environment variable to be deleted.

Normal Return

0.

Error Return

-1 and errno is set to EINVAL.

Programming Considerations

Examples

The following examples set up and print environment variable _EDC_ANSI_OPEN_DEFAULT.

#include <stdio.h>
#define _POSIX_SOURCE
#include <stdlib.h>
 
int main(void)
{
   char *x;
 
   /* set environment variable _EDC_ANSI_OPEN_DEFAULT to "Y" */
   setenv("_EDC_ANSI_OPEN_DEFAULT","Y",1);
 
   /* set x to the current value of the _EDC_ANSI_OPEN_DEFAULT*/
   x = getenv("_EDC_ANSI_OPEN_DEFAULT");
 
   printf("program1 _EDC_ANSI_OPEN_DEFAULT = %s\n",
      (x != NULL) ? x : "undefined");
 
   /* call the child program */
   system("program2");
 
   /* set x to the current value of the _EDC_ANSI_OPEN_DEFAULT*/
   x = getenv("_EDC_ANSI_OPEN_DEFAULT");
 
   printf("program1 _EDC_ANSI_OPEN_DEFAULT = %s\n",
      (x != NULL) ? x : "undefined");
}

Output

program1 _EDC_ANSI_OPEN_DEFAULT = Y
program1 _EDC_ANSI_OPEN_DEFAULT = Y

Y
The value defined for the environment variable.

The following example, which is a child of the previous example, is started by a system call. Like the previous example, this example sets up and prints the value of environment variable _EDC_ANSI_OPEN_DEFAULT or, as in this case, indicates that the value is undefined. This example shows that environment variables are propagated forward to a child program, but not backward to the parent.

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
   char *x;
 
   /* set x to the current value of the _EDC_ANSI_OPEN_DEFAULT*/
   x = getenv("_EDC_ANSI_OPEN_DEFAULT");
 
   printf("program2 _EDC_ANSI_OPEN_DEFAULT = %s\n",
      (x != NULL) ? x : "undefined");
 
   /* delete the Environment Variable */
   unsetenv("_EDC_ANSI_OPEN_DEFAULT");
 
   /* set x to the current value of the _EDC_ANSI_OPEN_DEFAULT*/
   x = getenv("_EDC_ANSI_OPEN_DEFAULT");
 
   printf("program2 _EDC_ANSI_OPEN_DEFAULT = %s\n",
      (x != NULL) ? x : "undefined");
}

Output

program2 _EDC_ANSI_OPEN_DEFAULT = Y
program2 _EDC_ANSI_OPEN_DEFAULT = undefined

Y
The value defined for the environment variable.

undefined
The environment variable is not defined.

Related Information