Reputation: 279
Here is my test code , I don't give the function a return value, but why this code can pass through the compiler? And I wonder if I don't give the explicit return type to one function like below, what the compiler will generate?
Here is the test code,Thanks.
#include <iostream>
#include <vector>
using std::vector;
vector<vector<int> > testReturn(){
int test = 5;
}
int main(){
testReturn();
return 0;
}
Upvotes: 0
Views: 181
Reputation: 726539
I don't give the function a return value,but why this code can pass through the compiler?
Providing a return
value is optional in C. This rule "migrated" to C++ as well, adding to a long list of undefined behaviors (i.e. situations when invalid programs are allowed to compile). To C++'s credit, compilers do warn you about situations like this in rather unambiguous terms.
And I am wonder if i don't give the explicit return type to one function like below, what's the compiler will generate the code?
The compiler will not generate any code for handling the return value. Whatever is the arbitrary state of the CPUs registers and the memory at the closing brace, that's the state that is going to be "returned". An attempt to interpret arbitrary values as the return value is what's going to cause the crash.
Upvotes: 1
Reputation: 8866
This is an incorrect code, producing undefined behavior.
Such code (function with return type bit without actual return statement) does compile in some variations with some compilers. This, however, means nothing but that there is a bug in the compiler, which should give a warning/error instead.
Upvotes: 1
Reputation: 50667
You cannot always trust the compiler as different compilers have different checking conditions while compiling. If you don't return in a function that need to return, even compiled successfully, the result is undefined. This is why your program crash. You should always try to avoid this.
Upvotes: 1
Reputation: 59997
The code does not compile as the return type of testRunner
is a vector of a vector of ints.
So return it!
Upvotes: 0