简体   繁体   English

C ++是否允许函数的默认返回类型?

[英]Does C++ allow default return types for functions?

In C the following horror is valid: 在C中,以下恐怖是有效的:

myFunc()
{
  return 42;  // return type defaults to int.
}

But, what about in C++? 但是,在C ++中呢? I can't find a reference to it either way... 无论如何我都找不到它的参考...

My compiler (Codegear C++Builder 2007) currently accepts it without warning, but I've had comments that this is an error in C++. 我的编译器(Codegear C ++ Builder 2007)目前在没有警告的情况下接受它,但我已经注意到这 C ++中的错误。

It's ill-formed in C++. 它是病态的在C ++中。 Meaning that it doesn't compile with a standard conforming compiler. 这意味着它不能使用标准的符合编译器进行编译。 Paragraph 7.1.5/4 in Annex C of the Standard explains the change "Banning implicit int". 标准附件C第7.1.5 / 4段解释了“禁止隐含int”的变化。

Implicit return types are valid in C89, but a lot of compilers warn about it. 隐式返回类型在C89中有效,但许多编译器都对此提出警告。

They are not valid in C++, nor in C99. 它们在C ++和C99中都无效。

So, it's definitely 'ill formed' C++, but it seems many compilers accept it with a warning at best. 所以,它肯定是“形成错误的”C ++,但似乎许多编译器最多只接受警告。

  • Codegear C++Builder 2007: No error or warning at all Codegear C ++ Builder 2007:完全没有错误或警告
  • G++: Requires -W -Wall to generate warning , or -pedantic to generate error (Piotr) G ++:需要-W -Wall生成警告,或者-pedantic生成错误(Piotr)
  • MSVC 8: produces an error ( tfinniga ) MSVC 8:产生错误( tfinniga
  • others...? 其他...?

Please add to/correct this list! 请添加/更正此列表!

这不是合法的C ++,但是一些编译器会以静默方式或使用诊断方式接受它。

As posted, it is ill-formed. 如发布,它是不正确的。 MSVC 8 gives the following error: MSVC 8给出以下错误:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM