Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
Fahad Siddiqui Avatar asked Dec 20 '22 15:12

Fahad Siddiqui


2 Answers

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.

like image 151
Sergey Kalinichenko Avatar answered Dec 31 '22 02:12

Sergey Kalinichenko


Attributes are a new feature in C++11. Compiler vendors have long offered vendor-specific extensions that allow you to annotate functions in some way or another, but now there is a standard mechanism. There aren't many actual attributes specified by the standard (only noreturn and carries_dependency), but the mechanism for annotating functions is standardized now at least.

That said, the noreturn attribute has non-trivial semantics: If a function declared with this attribute does actually return, the program has undefined behaviour. Compilers should (but don't have to) produce a diagnostic if they can tell that you are returning from a noreturn function. The attribute is valuable to allow optimizations and better diagnostics.

like image 22
Kerrek SB Avatar answered Dec 31 '22 00:12

Kerrek SB