C ++ 11 Do all control paths need to return a value?

It seems to me that this is a ridiculous question, but today I wrote a member function in C ++ that should return int, but not always. I even wrote a very simple function that does not return a value ...

int derp() { if (11 == 22) return 0; } 

Is this a recent change? is my compiler broken? lol

EDIT: this compiles btw

+4
source share
2 answers

In a non-empty function, all control paths must return. The key problem here is that the compiler is not required to diagnose it. Please note that compilation and correctness are not necessarily the same. All correct compilation of code, but not all of the code that compiles, is correct.

+7
source

No, C ++ never required all control paths to return a value. It is valid for C ++ 11 and C ++ 03 (syntactically).

Some compilers can detect most situations where you do not have enough return, but diagnostics are not required. Most of them will not issue a diagnosis if at least the control path returns.

Regardless, this is UB.

+4
source

All Articles