argc 在 POSIX 系统上可以为零吗?

标签 c posix language-lawyer program-entry-point

给定主程序的标准定义:

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

在 POSIX 系统上什么情况下 argc 可以为零?

最佳答案

是的,这是可能的。如果你调用你的程序如下:

execl("./myprog", NULL, (char *)NULL);

或者:

char *args[] = { NULL };
execv("./myprog", args);

然后在“myprog”中,argc 将为 0。

The standard还特别允许 0 argc,如第 5.1.2.2.1 节中关于托管环境中的程序启动所述:

1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) { /* ... */ } 

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

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

or equivalent; or in some other implementation-defined manner.

2 If they are declared, the parameters to the main function shall obey the following constraints:

  • The value of argc shall be nonnegative.
  • argv[argc] shall be a null pointer.

...

另请注意,这意味着如果 argc 为 0,则 argv[0] 保证为 NULL。然而,标准中并未详细说明 printf 在用作 %s 说明符的参数时如何处理 NULL 指针。在这种情况下,许多实现会输出“(null)”,但不能保证。

关于argc 在 POSIX 系统上可以为零吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49817316/

相关文章:

c - 将 ip 的十六进制值转换为标准格式

c - 为什么这两个 execvp 会产生不同的结果?

c++ - 一个默认的默认构造函数,为什么不是用户提供的默认构造函数呢?

c++ - std::function 中的冗余构造函数重载?

c - 结构包装是确定性的吗?

检查字符串中元音的出现

c - "Assignment to expression with array type"错误

c - 添加学生人数

Perl POSIX 返回错误的年份

c++ - C++ 函数签名中 `struct` 的使用定义良好吗?