code snippet:
#include <iostream>
int main()
{
std::function<int(int)> func = [](int data)->int{
std::cout << "this is " << data << "\n";
};
func(3);
}
output
this is 3
I expected the above not to compile at all, but to my supprise it did compile. the compiler only generated this warning:
main.cpp:7:5: warning: non-void lambda does not return a value [-Wreturn-type]
};
^
1 warning generated.
My question is why wasnt a compile error generated?
My question is why wasnt a compile error generated?
Reaching the closing }
of any usual function that is declared to have a non-void
return type causes undefined behavior. The compiler does not have to diagnose this at all and in fact cannot generally do that (since it is an undecidable problem). It can't make it an error instead of a warning in general either, because it would need to prove that the function is actually called with the problematic execution path. If the function is never called in such a way that it will reach the closing }
, then the program still has well-defined behavior and is not ill-formed.
The body of a lambda is nothing but the body of the operator()
member function of the closure type generated from the lambda and the same rules apply to it. The return type declared on the lambda expression is the return type declared on this operator()
member function.