1

I am aware that the main function can take two arguments: int argc and char* argv[]. This is well documented. However the main function can also take a third argument. Does anyone one know what this argument is?

Lucas
  • 523
  • 2
  • 10
  • 20

4 Answers4

3

It's the environment variables, and have the same type as the normal argv. It's not part of the C++ standard though, but may still work on some systems.

It's from older UNIX systems, where the environment variables often was passed like this.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    envp is always passed, at least on unix (and it works today too due to historical and backward-compatible reasons) – Zaffy Feb 28 '13 at 12:35
  • Even if it didn't pass to C++, you could always just write your entry points in C and have it call your C++ program, right? – Bingo Feb 28 '13 at 12:40
  • @Bingo The `main` function in both C and C++ should be called the same by the run-time system. So it's usable in both C and C++, but unportable outside the UNIX world. – Some programmer dude Feb 28 '13 at 12:42
  • Perhaps for elaboration. Does the programmer need an int envc as an equivelent for argc, so that the programmmer can see how many envrironment variables are passed to the program. Or is char env[] sentinalled with a NULL pointer? – hetepeperfan Feb 28 '13 at 12:51
  • @hetepeperfan There's no `envc`, but the array is terminated by a `NULL` just like `argv`. – Some programmer dude Feb 28 '13 at 12:54
3

The function main may have also a forth argument on Mac OS, of the form char **apple, "containing arbitrary OS-supplied information". See http://en.wikipedia.org/wiki/Main_function#C_and_C.2B.2B for details.

damisan
  • 1,037
  • 6
  • 17
2

There are only two forms of main which are required to be supported, and which are portable to all platforms. But an implementation can add any additional forms it wants: int main( double ) would be legal, for example (although I've never heard of an implementation which uses it), as would int main( char const* arg0... ). In practice, "classical" Unix would support int main( int argc, char** argv, char** environ ); this is not required by Posix, and presumably, there are some Unix which don't support it. Outside of the Unix world, many early C implementations tried to look like Unix, and so may also support this (today more for reasons of backwards compatibility than to look like Unix).

It's not something you can count on, however.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
0

You can pass char *env[], it need not be named like this, though, in order to pass a different set of environment-variables. You can change the environment the particular process is executing in.

See this article, there is an explanation.

bash.d
  • 13,029
  • 3
  • 29
  • 42