gpt4 book ai didi

c++ - 可以省略 main 函数中的返回类型吗?

转载 作者:IT老高 更新时间:2023-10-28 21:55:08 25 4
gpt4 key购买 nike

main函数的声明有什么特殊的规则吗?

根据ideone这是合法的 C++:

main()  // As opposed to int main()
{
return 0;
}

另一方面,普通函数似乎没有特权避免返回类型:

f(){} 

int main()
{
return 0;
}

给出错误:

prog.cpp:1:3: error: ISO C++ forbids declaration of 'f' with no type [-fpermissive] f(){} ^

main函数在这种情况下有什么特殊吗?

最佳答案

永远不要省略 main 的返回类型,因为它是非标准的!


wandbox example :

prog.cc:1:6: warning: ISO C++ forbids declaration of 'main' with no type [-Wpedantic] main()


From $3.6.1 :

1 A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [ Note: In a freestanding environment, start-up and termination is implementation-defined; startup contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. — end note ] § 3.6.1 58

2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined

关于c++ - 可以省略 main 函数中的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39789054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com