I've never seen [[ noreturn ]] used on non-void returning functions before.
Is the following well defined?
[[ noreturn ]] int function();
int function(){
while(true){/* impl */}
return 0;
}
The reason the return type must be int
, is because the function is passed to another function via a function pointer.
So assuming the caller looks something like this:
//call the non-returning function
int var = (*fptr)();
//use var some way (even though the function will never actually return)
std::cout << var;
will this exhibit any kind of undefined behavior?
The standard specification on [[noreturn]]
is in [dcl.attr.noreturn]. The entire normative texts reads:
The attribute-token
noreturn
specifies that a function does not return. It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present. The attribute may be applied to the declarator-id in a function declaration. The first declaration of a function shall specify thenoreturn
attribute if any declaration of that function specifies thenoreturn
attribute. If a function is declared with thenoreturn
attribute in one translation unit and the same function is declared without thenoreturn
attribute in another translation unit, the program is ill-formed; no diagnostic required.If a function
f
is called wheref
was previously declared with thenoreturn
attribute andf
eventually returns, the behavior is undefined.
There is no mention of return type. The only thing that matters is that the function not return. If the function returns (whether void
or int
or vector<vector<double>>
), then behavior is undefined. If the function doesn't return, the return type is immaterial.
From the C++ standard §7.6.8/p2 Noreturn attribute [dcl.attr.noreturn] (Emphasis Mine):
If a function f is called where f was previously declared with the noreturn attribute and f eventually returns, the behavior is undefined. [ Note: The function may terminate by throwing an exception. — end note ] [ Note: Implementations are encouraged to issue a warning if a function marked [[noreturn]] might return. — end note ]
Since your function will never reach the return 0;
there's no UB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With