C++main函数的两种写法
1,返回值为int,且main不带参数
- #include<iostream>
- using namespace std;
-
- int main()
- {
- cout << "Hello C++ \n" << endl;
- system("pause");
- return 1;//函数返回值取值范围0到255,因为保存返回值使用8bit二进制无符号补码的形式存储的;
- }
2,返回值为int,且main函数带参数
- #include<iostream>
- using namespace std;
- int main(int args, char* agrv[])
- {
- cout << "Hello C++ " << endl; //自动换行
- system("pause");
- return 1;//函数返回值取值范围0到255
- }
3,返回值为int,且参数为void的main函数
- #include<iostream>
- using namespace std;
-
- int main(void)
- {
- cout << "hello C++" << endl;
- system("pause");
- return 1;//函数返回值取值范围0到255
- }
4,返回值为void,且参数为void的main函数
- #include
- using namespace std;
-
- void main(void)
- {
- cout << "hello C++" << endl;
- system("pause");
- }
5,返回值为void,且无参数的main函数
- #include
- using namespace std;
-
- void main() {
- cout << "hello C++" << endl;
- system("pause");
- }
二,测试main函数的参数
1,编写如下代码
文件名为hello.cpp
- #include
- using namespace std;
-
- int main(int argc, char* agrv[])
- {
- cout << "argc = " << argc << endl;
- for (int i = 0; i < argc; i++) {
- cout << agrv[i] << endl;
- }
- system("pause");
- return 1;
- }
使用Windows命令行,切换到hello.cpp 文件所在目录,执行如下命令
g++ hello.cpp -o hello
2,运行生成hello.exe,命令行中直接输入hello回车即可;
结果如下
命令行中输入hello -ss mm 运行如下
总结,所以main函数中的argc参数其实是命令行运行程序是输入的参数个数,其中包括文件名,外加后面跟着的参数个数;agrv参数就是命令中输入的参数具体值组成的字符串;
使用VisualStudio运行如下代码结果如下,参数就一个文件名,及文件名组成字符串参数;