Search code examples
c++c++11noreturn

What is meant by an attribute of a function?


What this C++11 syntax means?

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

The C++ Standard Working Draft n3797 states,

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.

What is meant by an attribute of a function?


Solution

  • A function is defined by its name, its return type, and a list of formal parameters, along with their types. These items constitute the "interface" of the function: they are important to the caller of the function, because they define the way to invoke it.

    Attributes, on the other hand, provide a way to tell the compiler additional things about the function that do not alter its interface. When the compiler knows that a function is

    • An interrupt handler, or
    • A pure function (i.e. with no side effects or references to state of any kind), or
    • A function that returns twice (similar to fork), or
    • A function that never returns, etc.

    the compiler can optimize the code better, and provide additional warnings / silence unnecessary warnings.

    For example, if you write

    main() {
        f();
        g();
    }
    

    and f() is marked noreturn, the compiler will issue a warning about the call of g() being unreachable.