c++一个问题

int main(int a)
{
cout<<a<<endl;
return 0;
}
输出结果为1
为什么a会默认为a= 1;

不知道谁想出来的问题,但是感觉不和规范吧。
C++标准写法常见有两种
int main ()
int main ( int argc, char *argv[] )
argc是指命令行输入参数的个数,argv用来存储参数的字串,不管后面有几个参数第一个参数肯定是程序名,所以argc至少是1,后面没有参数那么就等于1。所以第一个参数是传入的是1,你这种形式虽然少了第二个参数,但是一个参数仍然传进来了,自然就是1。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-06-08
你看看这个英文的关于main( int argc, char *argv[ ], char *envp[ ] )里边参数的介绍:
argc

An integer specifying how many arguments are passed to the program from the command line. Because the program name is considered an argument, argc is at least 1.
译为:
  argc     一个整数用来指定多少参数被传递给程序的命令行。因为程序的名字被当作是一个参数,所以argc是至少1。

argv

An array of null-terminated strings. It can be declared as an array of pointers to char or as a pointer to pointers to char.The first string (argv[0]) is the program name, and each following string is an argument passed to the program from the command line. The last pointer (argv[argc]) is NULL.
译为:以null结尾的字符串的数组。它可以被声明为一个数组的指针作为一个指针字符或字符指针。第一个字符串(argv[0])是程序的名字,和每个以下字符串是一个参数传递给程序的命令行。最后的指针(argv[i])是NULL。追问

谢谢

第2个回答  2017-01-14
定义主函数
int main(int argc, int **argv)
这样的形式的时候
argv不可能等于NULL
至少有一个运行的程序名。
至于最后一个argv为NULL ,只是部分平台有这个功能
有些是没有的
大多数情况下, 还是要用argc来判断个数。

除此外, 很多程序, 会根据参数的个数实现不同功能, 直接用argc来判断, 比循环遍历argv确定参数总个数要方便的多。
相似回答