3
int main(int argc, char **argv)
{}
  1. Is it possible that argc equals 0?

  2. Must argv[0] be the executable file's name?

  3. Is there any standard for these issues?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 2
    The relevant information is all in this answer to [What should `main()` return in C and C++?](http://stackoverflow.com/a/18721336/15168). – Jonathan Leffler Jun 09 '15 at 07:19

2 Answers2

6
  1. Yes.

  2. Normally yes, it could also be empty, or some other identifying string, or even NULL (see my addendum). It's also possible to change argv[0] to something else from inside the program.

  3. The C (and C++) specifications.

You also missed one: The last element in argv is always NULL, meaning argv[argc] will always be NULL.


In the C11 specification it's in §5.1.2.2.1 Program startup.

In the C++11 specification its §3.6.1 Main function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 3
    2. No; if it is not possible to determine the executable name, `argv[0]` may be a pointer to an empty string. That said, it is more of a theoretical than practical statement. – Jonathan Leffler Jun 09 '15 at 07:18
  • 1
    And, on rereading the standards quoted in the duplicate, `argc` is permitted to be zero in both C and C++; I had forgotten that detail. – Jonathan Leffler Jun 09 '15 at 07:23
  • @JonathanLeffler I was just about to update my answer before, but then had to go to a meeting. Updated now though. :) – Some programmer dude Jun 09 '15 at 08:14
1
  1. Yes
  2. No. Argv[0] don't have to exist, but if it does it is a program name, given it could be obtained.
  3. I guess this is standard in C, Cpp. @JonathanLeffler linked a great answer.
MKK
  • 130
  • 10
  • Go check what the standards say in the duplicate question. I'd forgotten about the possibility of `argc == 0` but the standards (both C and C++) explicitly allow it. The value of `argv[0]` may be an empty string instead of the program name, assuming `argc > 0` — but only if it is impossible to tell the program name on the particular platform. That is seldom a practical problem in hosted environments. – Jonathan Leffler Jun 09 '15 at 07:25
  • Thank you, that is actually quite surprising for me. You learn whole life :P – MKK Jun 09 '15 at 07:30
  • It surprised me, too. As I said, I'd forgotten until I went to read once more... – Jonathan Leffler Jun 09 '15 at 07:32