Can argc be zero on a POSIX system?

前端 未结 6 1388
暖寄归人
暖寄归人 2021-02-04 23:04

Given the standard definition for the main program:

int main(int argc, char *argv[]) {
   ...
}

Under which circumstances can argc

6条回答
  •  失恋的感觉
    2021-02-04 23:41

    Yes, it can be zero, meaning that argv[0] == NULL.

    It's a convention that argv[0] is the name of the program. You can have argc == 0 if you launch yourself the binary, like with execve family and don't give any argument. You can even give a string that is nowhere near to be the program name. That's why using argv[0] to get the name of the program is not entirely reliable.

    Usually, the shell where you type your command-line always add the program name as the first argument, but again, it's a convention. If argv[0] == "--help" and you use getopt to parse option, you will not detect it because optind is initialized to 1, but you can set optind to 0, use getopt and "help" long option will show up.

    long story short : It's perfectly possible to have argc == 0 (argv[0] is not really special by itself). It happen when the launcher doesn't give argument at all.

提交回复
热议问题