Wow... I'm at a loss for words. I've been programming in C/C++ for nearly a decade and I just found this little bit of information today. I happened to be reviewing the documentation for the execve() system call on Mac OS X and I noticed that it mentioned that main() gets passed three arguments, not two:
main( int argc, char** args, char** env )
The third argument is a NULL terminated array of environment variables (the same format as char** args in other words. Now, the normal way to find an environment variable would be to call getenv() with the name of the variable you want, but printing the environment variables passed in could be interesting:
#include <iostream>

int main( int argc, char** args, char** env )
{
      int i = 0;
      while( env[i] != NULL )
      {
         std::cout << env[i] << std::endl;
         i++;       }
     return 0;
}

No teacher or book ever mentioned that main() can take more than two arguments. My guess is that this is OS dependent. Which would explain why it is never mentioned or explained in books.

I don't immediately see how browsing through the environment variables could be useful, but then I never knew it was possible before... maybe I'll think of a use for it later.

What else is out there? How about another NULL terminated list? It looks like this is the command that was called - but why again, this is normally in argv[0]?

#include <iostream>

int main( int argc, char** args, char** env, char** whatisthis )
{
      int i = 0;
      while( whatisthis[i] != NULL )
      {
         std::cout << whatisthis[i] << std::endl;
         i++;       }
     return 0;
}
Windows also supports the extra arguments in main.

 

Add to My Yahoo!

Add to Google

Subscribe with Bloglines

Austin Gilbert/Male/26-30. Lives in United States/Oklahoma/Tulsa/Midtown, speaks English. Spends 40% of daytime online. Uses a Fast (128k-512k) connection. And likes computer science/photography.
This is my blogchalk: United States, Oklahoma, Tulsa, Midtown, English, Austin Gilbert, Male, 26-30, computer science, photography.

You think you know something about C/C++?
2006/12/30