Reputation: 35515
Is this code defined behavior?
inline int a() { return 0 + a(); }
int main() { a(); }
If optimizations are enabled then Clang optimizes it out but GCC doesn't. So the code is not portable in practice. Does the C++ spec say anything about this?
Upvotes: 0
Views: 162
Reputation: 385295
As I discuss in this answer, regardless of the presence of the inline
keyword, the behaviour of your code is certainly undefined since you call this function:
[C++11: 1.10/24]:
The implementation may assume that any thread will eventually do one of the following:
- terminate,
- make a call to a library I/O function,
- access or modify a volatile object, or
- perform a synchronization operation or an atomic operation.
Clang is permitted to elide the entire thing, just as GCC is permitted to run it without inlining and reach a stack overflow. A compiler would also be free to attempt actual inlining, and it is even permitted to crash during compilation in such a case.
Crucially, there is no rule in the standard that makes the semantics for an infinite recursion differ just because a function is marked inline
or even actually inlined ([C++11: 7.1.2]
).
Of course, I reckon that if you were to never invoke this function, by the as-if rule a compiler can elide it entirely and then you have no problem.
Upvotes: 3