Open In App

_Noreturn function specifier in C

Last Updated : 17 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C, the _Noreturn specifier is used to indicate that a function does not return a value. It tells the compiler that the function will either exit the program or enter an infinite loop, so it will never return control to the calling function. This helps the compiler to optimize code and issue warnings if a function with _Noreturn is incorrectly expected to return a value.

Note: This feature is deprecated. [[noreturn]] attribute should be used instead.

Let’s take a look at an example:

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

_Noreturn void func() {
    printf("Exiting program...\n");
  
    // Terminate the program without returning
    exit(0);  
}

int main() {
    printf("Program started.\n");
  
    // This will not return control back to main
    func(); 
    printf("This line will never be reached.\n");
    return 0;
}

Output
Program started.
Exiting program...

Explanation: In this example, the function func() is marked with the _Noreturn specifier because it calls exit(0), which terminates the program. As a result, the program does not return control to main(), and the line printf(“This line will never be reached.”) is never executed.

Syntax

_Noreturn void functionName() {
// Code that does not return
}

Example for Using _Noreturn with Infinite Loops

C
#include <stdio.h>

// Function with infinite loop
_Noreturn void func() {
    while (1)
        printf("GfG\n");
}

int main() {
  
    // This will run infinitely, no return to main
    func(); 
  
    // These line will never be reached
  	printf("Came back to main()");
    return 0;  
}


Output:

GfG
GfG
.
.
infinite

Explanation: In this example, func() runs an infinite loop. Since the function does not exit the loop, the program control never returns to main(). The _Noreturn specifier informs the compiler that this function will never return.


Next Article

Similar Reads