在POSIX系统上argc可以为零吗? [英] Can argc be zero on a POSIX system?

查看:70
本文介绍了在POSIX系统上argc可以为零吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出主程序的标准定义:

Given the standard definition for the main program:

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

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

Under which circumstances can argc be zero on a POSIX system?

推荐答案

是的,有可能.如果您按以下方式调用程序:

Yes, it is possible. If you call your program as follows:

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

或者:

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

然后在"myprog"中,argc将为0.

Then in "myprog", argc will be 0.

标准也专门允许关于主机环境中程序启动的第5.1.2.2.1节中所述的0 argc:

The standard also specifically allows for a 0 argc as noted in section 5.1.2.2.1 regarding program startup in a hosted environment:

1 在程序启动时调用的函数名为main.该实现没有为此函数声明任何原型.应该是 定义为返回类型为int且没有参数:

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) { /* ... */ } 

或具有两个参数(此处称为argcargv,尽管可以使用任何名称,因为它们是本地名称 到声明它们的函数):

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 如果已声明,则main函数的参数应遵循以下约束:

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

  • argc的值应为非负数.
  • argv[argc]应为空指针.
  • The value of argc shall be nonnegative.
  • argv[argc] shall be a null pointer.

...

还请注意,这意味着如果argc为0,则保证argv[0]为NULL.但是,在标准中没有明确说明printf在用作%s说明符的参数时如何处理NULL指针.在这种情况下,许多实现都将输出(null)",但我不认为这是可以保证的.

Note also that this means that if argc is 0 then argv[0] is guaranteed to be NULL. How printf treats a NULL pointer when used as the argument to a %s specifier is not spelled out in the standard however. Many implementations will output "(null)" in this case but I don't believe it's guaranteed.

这篇关于在POSIX系统上argc可以为零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆