use*_*570 3 c++ program-entry-point language-lawyer
我正在学习 C++,并了解到以下给定的声明是等效的:
int main (int argc, char *argv[]); //first declaration
int main (int argc, char **argv); //RE-DECLARATION. Equivalent to the above declaration
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我将声明更改为:
//note the added const
int main (int argc,const char *argv[]); //IS THIS VALID?
Run Code Online (Sandbox Code Playgroud)
上面我添加 const 的声明有效吗?也就是说,C++ 标准是否允许这种带有添加的 const 的修改声明。
添加const会更改函数的类型。它不是同一函数的声明。
这是否main特别有效,取决于语言的实现:
[基本.启动.main]
实现不应预定义主函数。其类型应具有 C++ 语言链接,并且应具有声明的 int 类型返回类型,但除此之外,其类型是实现定义的。实施应允许两者
- () 返回 int 的函数和
- (int, 指向 char 的指针) 返回 int 的函数
作为 main 的类型 ([dcl.fct])。
理论上它在某些实现中可能是有效的,但它不能移植到所有系统。
根据 cppreference.com ( main_function ),main应该具有以下形式之一:
int main () { body } (1)
int main (int argc, char *argv[]) { body } (2)
/* another implementation-defined form, with int as return type */ (3)
Run Code Online (Sandbox Code Playgroud)
使用int main (int argc,const char *argv[])(您建议的变体)可以在 MSVC 中使用。本案属于上述表格(3)。
但既然是这样,implementation-defined最好避免(即使在您当前的环境中有效)。
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |