Question

I've read the libc reference for int main (int argc, char *argv[]), as well as section 3.6.1 "Main function" in the current working standard of the C++ ISO documentation. I've also read a bunch about references. I understand they cannot be reassigned, that they must be only one layer deep, etc.

That said, why is the standard int main (int argc, char *argv[]) rather than int main (int argc, char * &argv) such that it is an "array"/data block holding the references to the parameters?

What I mean by this is why have an array of arrays (char **argv) that are NOT owned by a program and COULD be changed/moved during run time instead of memory that by its definition cannot be modified without the program's consent and proper handling (for example via signaling)? What am I missing?

Was it helpful?

Solution

First of, consider char* to mean c_string, and it immediately becomes obvious why you would need int main(int argc, c_string argv[]) versus int main(int argc, c_string& argv). After all, programs can take more than one parameter.

Since an array of references (if it were allowed) would turn out to hold only a single char per index, since references cannot be used to find the next character (without taking the reference of it, and thus converting it to a pointer), this does not make any sense either.

The assumption that the array of arguments is not owned by the program is simply false. The C standards 1999 and 2011 explicitly say:

The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

And my copy of the C++1y standard draft says nothing to the contrary.

OTHER TIPS

As @Red Alert said you have confused the redeclaration of "main" but I'm going to answer what I think you asked.

The program arguments is provided by the operating system, and thus is not actually owned by the program. Remember that C/C++ is intended to be low level and efficient so extra copies of arguments should be avoided. I have not seen anyone actually change them on a running program but there are several ways in e.g. Linux to retrieve them outside of the program.

Also think of compatibility with C, you have not got the "&" operator in that way in C and the "main" declaration is inherited from C.

First, there's no such thing as "array of references" in C++. The standard explicitly prohibits it (§8.3.2 [dcl.ref]/5):

There shall be no references to references, no references to arrays of runtime bound, no arrays of references, and no pointers to references.

Second, even if there were such a thing, backward compatibility requirements would weigh extremely heavily against such a change, which would break lots and lots of existing code using int main(int argc, char *argv[]) for no good reason.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top