c++c++11returnundefined-behaviornoreturn

Can I use [[noreturn]] on non-void returning functions?


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?


Solution

  • 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 the noreturn attribute if any declaration of that function specifies the noreturn attribute. If a function is declared with the noreturn attribute in one translation unit and the same function is declared without the noreturn attribute in another translation unit, the program is ill-formed; no diagnostic required.

    If a function f is called where f was previously declared with the noreturn attribute and f 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.