问题描述
如果函数的返回类型不是 void
,并且该函数不返回任何东西,则我猜编译器将返回垃圾值(可能被视为未初始化的值)值)。它在编译时发生,所以为什么不显示错误?
If a function has a return type other than void
, and the function does not return anything, then I guess the compiler returns a garbage value (possibly seen as an uninitialized value). It happens at compile time, so why shouldn't it show an error?
例如,
int func1() {
return; // error
}
int func2() {
// does not return anything
}
第二个 func2
应该抛出错误,但不会。有什么理由吗?我的想法是,可以将其视为未初始化的值,因此,如果在第二种情况下需要引发错误,则在未初始化的情况下抛出错误,例如
The second func2
should throw an error, but it does not. Is there a reason for it? My thinking was such that, it can be seen as an uninitialized value, so if we need to throw an error in the second case, then we need to throw error, if an value is uninitialized, say
int i; // error
int i = 6; // okay
任何想法,还是重复的问题?感谢您的帮助。
Any thoughts, or is this a duplicate question? I appreciate your help.
推荐答案
在C ++中,此类代码具有未定义的行为:
In C++, such code has undefined behaviour:
大多数编译器会针对类似问题的代码产生警告。
Most compilers will produce a warning for code similar to that in the question.
C ++标准并不要求这是编译时错误,因为在一般情况下,很难正确地确定代码是否实际上在函数末尾运行,或者函数是否通过异常(或longjmp或类似机制)。
The C++ standard does not require this to be a compile time error because in the general case it would be very difficult to correctly determine whether the code actually runs off the end of the function, or if the function exits through an exception (or a longjmp or similar mechanism).
考虑
int func3() {
func4();
}
如果 func4()
抛出,那么这段代码就可以了。编译器可能看不到 func4()
的定义(由于单独的编译),因此无法知道它是否会抛出。
If func4()
throws, then this code is totally fine. The compiler might not be able to see the definition of func4()
(because of separate compilation), and so cannot know whether it will throw or not.
此外,即使编译器可以证明 func4()
不会抛出,它仍然必须证明<$ c $实际上会调用c> func3()来合法拒绝该程序。这种分析需要检查整个程序,这与单独的编译不兼容,并且在一般情况下甚至是不可能的。
Furthermore, even if the compiler can prove that func4()
does not throw, it would still have to prove that func3()
actually gets called before it could legitimately reject the program. Such analysis requires inspection of the entire program, which is incompatible with separate compilation, and which is not even possible in the general case.
这篇关于如果函数不返回任何值,且返回类型为有效,编译器是否可以返回垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!