Namespaces
Variants
Views
Actions

Function specifiers

From cppreference.com
< c‎ | language
Revision as of 18:34, 31 May 2013 by P12bot (Talk | contribs)

Used in the declaration of functions.

  • inline (since C99) - suggestion to the compiler to "inline" the function, making calls to it as fast as possible.
  • _Noreturn (since C11) - specifies that the function does not return to where it was called from.

Contents

Syntax

inline function_declaration
_Noreturn function_declaration

Explanation

inline (since C99)

The inline keyword is a hint given to the compiler to perform an optimization. The compiler has the freedom to ignore this request.

If the compiler inlines the function, it replaces every call of that function with the actual body (without generating a call). This avoids extra overhead created by the function call (placing data on stack and retrieving the result) but it may result in a larger executable as the code for the function has to be repeated multiple times. The result is similar to function-like macros

The function body must be visible in the current translation unit.

inline Example

inline int sum(int a, int b) {
  return (a + b);
}
 
int c = sum(1, 4);
// If the compiler inlines the function the compiled code will be the same as writing:
int c = 1 + 4;


_Noreturn (since C11)

The _Noreturn keyword states that the function that follows it does not return to the function that it was called from. The compiler will typically generate a warning if a function declared with _Noreturn attempts to return a value.

In the example below the stop_now() function is called, which causes the program to immediately terminate (unless the SIGABRT signal is caught). The code with the printf() and the return EXIT_SUCCESS; after the call to stop_now() is never executed and the execution never returns to the main() function, where stop_now() was called from.

_Noreturn Example

#include <stdlib.h>
#include <stdio.h>
 
_Noreturn void stop_now() {
  abort();
}
 
int main(void) {
 
  printf("Preparing to stop...\n");
 
  stop_now();
 
  printf("This code is never executed.\n");
 
  return EXIT_SUCCESS;
 
}

Output:

Preparing to stop...
Abort

Keywords

inline, _Noreturn

See Also

Storage class specifiers, abort()