main() 在 C 和 C++ 中应该返回什么? [英] What should main() return in C and C++?

查看:38
本文介绍了main() 在 C 和 C++ 中应该返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 和 C++ 中定义 main() 函数的正确(最有效)方法是什么 - int main()void main() — 为什么?那么论据呢?如果 int main() 那么 return 1 还是 return 0?

What is the correct (most efficient) way to define the main() function in C and C++ — int main() or void main() — and why? And how about the arguments? If int main() then return 1 or return 0?

这个问题有很多重复,包括:

  • What are the valid signatures for C's main() function?
  • The return type of main() function
  • Difference between void main() and int main()?
  • main()'s signature in C++
  • What is the proper declaration of main()? — For C++, with a very good answer indeed.
  • Styles of main() functions in C
  • Return type of main() method in C
  • int main() vs void main() in C

相关:

  • C++ — int main(int argc, char **argv)
  • C++ — int main(int argc, char *argv[])
  • Is char *envp[] as a third argument to main() portable?
  • Must the int main() function return a value in all compilers?
  • Why is the type of the main() function in C and C++ left to the user to define?
  • Why does int main(){} compile?
  • Legal definitions of main() in C++14?

推荐答案

main 的返回值指示程序如何退出.正常退出由 main 的 0 返回值表示.非零返回表示异常退出,但没有关于如何解释非零代码的标准.正如其他人所指出的,void main() 是 C++ 标准禁止的,不应使用.有效的 C++ main 签名是:

The return value for main indicates how the program exited. Normal exit is represented by a 0 return value from main. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, void main() is prohibited by the C++ standard and should not be used. The valid C++ main signatures are:

int main()

int main(int argc, char* argv[])

相当于

int main(int argc, char** argv)

还值得注意的是,在 C++ 中,int main() 可以不带返回语句,此时它默认返回 0.这对于 C99 程序也是如此.return 0; 是否应该省略还有待商榷.有效的 C 程序主签名的范围要大得多.

It is also worth noting that in C++, int main() can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0; should be omitted or not is open to debate. The range of valid C program main signatures is much greater.

效率不是 main 函数的问题.根据C++标准,它只能进入和离开一次(标记程序的开始和终止).对于 C,允许重新输入 main(),但应避免.

Efficiency is not an issue with the main function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering main() is allowed, but should be avoided.

这篇关于main() 在 C 和 C++ 中应该返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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