I am new to Linux. I came across this piece of code to print environmental variables. It is kind of confusing me. How can this code print the environmental variables?
#include <stdio.h>
extern char **environ;
int main()
{
char **var;
for(var=environ; *var!=NULL;++var)
printf("%s\n",*var);
return 0;
}
what is extern here?
If you don’t know what
externmeans, please find a book to learn C from. It simply means ‘defined somewhere else, but used here’.The
environglobal variable is unique amongst POSIX global variables in that it is not declared in any header. It is like theargvarray to the program, an array of character pointers each of which points at an environment variable in thename=valueformat. The list is terminated by a null pointer, just likeargvis. There is no count for the environment, though.So, on the first iteration,
varpoints at the first environment variable; then it is incremented to the next, until the value*var(achar *) is NULL, indicating the end of the list.That loop could also be written as: