Show: Delphi C++
Display Preferences

noreturn

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Syntax

FUNCTION NAME [[noreturn]]

Description

The noreturn attribute specifies that a function does not return; for example, functions that exit the application, execute an infinite loop, or throw exceptions. This means that the control flow does not go back to the calling function. If a function marked noreturn is called and eventually executes a return statement, the program is considered ill-formed, and the compiler generates an error.

For example:

void f [[noreturn]] () 
{
   throw "error";       // OK
}

void g [[noreturn]] (int i) 
{  // ill-formed
   if (i > 0)
      throw "positive";
}

In this example, the compiler generates an E2541 Error, because g returns void if i is less than or equal to 0.

The noreturn attribute is useful for a few library functions that cannot return, such as abort and exit. You can also define your own functions that never return by using the noreturn attribute.

For example:

void fatal(void) [[noreturn]];
void fatal(void)
{
   // ...
   exit(1);
}

The noreturn keyword tells the C++ compiler to assume that fatal cannot return. The compiler can then optimize without regard to what would happen if fatal ever did return. Thus, using noreturn can lead to better code. More importantly, it helps avoid spurious warnings of uninitialized variables. You cannot assume that registers saved by the calling function are restored before calling the function with the noreturn attribute. It does not make sense for a noreturn function to have a return type other than void.

Portability

POSIX  Win32  Win64  ANSI C  ANSI C++

deprecated

+

Note: The noreturn attribute is not supported by Clang-enhanced C++ compilers.

See Also

Personal tools
In other languages
Previous Versions
Assistance