Reason main-C isn't const

Viewed 150

I see the main() function usually called as:

  • int main(int argc, char** argv)
  • int main(int argc, char* argv[])
  • int main(void)

Related to these definitions:

  1. Technically speaking, for char** argv and char* argv[] is one preferred over the other or are these 100% interchangeable?
  2. Because both the argc and argument strings (should be?) immutable, why aren't they both const ? Or is this something that doesn't matter and it's just omitted out of convention/historical purpose? I suppose this could be done with: const char **argv = (const char **) argv; but curious why this isn't already done (would there be reasons for changing the arguments that are received, for example?)
3 Answers

Because they are both modifiable:

N1570 §5.1.2.2.1/2:

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.

  1. They are completely interchangeable.
  2. It is valid to modify them, sometimes there is a chain of command line processors in a program, and each removes the options relevant to it, before passing it on tho the next processor of the chain. In this case argc is passed into the processors via pointer. You can see an example, not in C but in C++ in the QT library: QApplication constructor.

There's a long discussion of the distinction (or non-distinction) between *argv[] and **argv here:

Should I use char** argv or char* argv[]?

Both are fairly widely used, and there's no practical difference between them in this particular context.

As for whether the pointers should be const are not -- that's an interesting, but rather academic debate. I'm a great believer in const-correctness in C, but main() is one place where I think it's counter-productive. It's idiomatic to write char **argv whether these pointers are really const or not, or whether your code treats them as constants or not. On Linux, they actually aren't constant -- a program can modify them, although there's rarely a need to.

My feeling is that if you write anything but char **argv or char *argv[], it's just going to cause confusion. I've recently seen examples where main() is defined to take char *argv[argc+1]. This is permissible with modern C compilers, but it's just not something C programmers are used to seeing.

Related