Is char *envp[] as a third argument to main() portable

Sangeeth Saravanaraj picture Sangeeth Saravanaraj · Apr 25, 2012 · Viewed 50.1k times · Source

In order to get an environment variable in a C program, one could use the following:

  • getenv()
  • extern char **environ;

But other than the above mentioned, is using char *envp[] as a third argument to main() to get the environment variables considered part of the standard?

#include <stdio.h>

int main(int argc, char *argv[], char *envp[])
{
    while(*envp)
        printf("%s\n",*envp++);
}

Is char *envp[] portable?

Answer

cnicutar picture cnicutar · Apr 25, 2012

The function getenv is the only one specified by the C standard. The function putenv, and the extern environ are POSIX-specific.

EDIT

The main parameter envp is not specified by POSIX but is widely supported.

An alternative method of accessing the environment list is to declare a third argument to the main() function:

int main(int argc, char *argv[], char *envp[])

This argument can then be treated in the same way as environ, with the difference that its scope is local to main(). Although this feature is widely implemented on UNIX systems, its use should be avoided since, in addition to the scope limitation, it is not specified in SUSv3.