_Noreturn function specifier in C

C has two function specifiers inline and _Noreturn. In this blog post, you will get the answer to the questions like:

  • What is _Noreturn in C?
  • When to use_Noreturn keyword?
  • Which header file includes the convenience macro noreturn?

Or any other. So, without further delay, let’s learn the _Noreturn keyword.

 

_Noreturn function specifier

_Noreturn is a function specifier which was introduced in C11. It specifies that a function declared with a _Noreturn function specifier does not return to its caller.

Example of _Noreturn function:

The following example demonstrates where the use of the _Noreturn keyword is valid.

Example 1:

Use of _Noreturn is valid with fun().

Why I am saying that is because the abort function causes abnormal program termination and control will not transfer to the caller.

_Noreturn void fun()
{
    abort(); 
}

Example 2:

Use of _Noreturn is Invalid with foo().

_Noreturn void foo(int i)
{
    if (i > 0)
    {
        abort();
    }
}

 

Now you are thinking why?

The reason is that if the value of i is less than or equal to zero (i<= 0), then control will transfer to the caller. And this is a primary condition of _Noreturn function specifier.

So if there is any probability for control flow to return to the caller, the function must not have the _Noreturn function specifier.

 

Points need to remember:

1. A function must not have the _Noreturn function specifier, if there is any probability for control flow to return to the caller,

2. If a function specified with _Noreturn function specifier eventually returns to its caller, either by using an explicit return statement or by reaching the end of the function body the behavior is undefined.

// causes undefined behavior if i < 0 or i > 0
_Noreturn void g (int i)
{
    if (i == 0)
    {
        abort();
    }
}

 

3. If the coder tries to return any value from that function that is declared as _Noreturn type, the behavior is undefined.

4. We can use the _Noreturn with convenience macro noreturn, which is provided in the header <stdnoreturn.h>.

#include <stdio.h>
#include <stdlib.h>
#include <stdnoreturn.h>

noreturn void fun()
{
    abort();
}

int main()
{
    fun();

    return 0;
}

 

5. The implementation will produce a diagnostic message for a function declared with a _Noreturn function specifier that appears to be capable of returning to its caller.

For example,

_Noreturn void testFun()
{
    puts("testFun");
}

You will get a warning message when compiling the code.

 

6. If it appears more than once the effect will be the same as if it appears once.

_Noreturn _Noreturn void fun()
{
    abort();
}

same as 

_Noreturn void fun()
{
    abort();
}

 

Recommended Post