Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
_Noreturn function specifier in C
The _Noreturn function specifier in C indicates to the compiler that a function will never return control to its caller. Functions marked with _Noreturn either terminate the program (using exit()) or run indefinitely (infinite loops). This helps the compiler optimize code and detect unreachable statements.
Syntax
_Noreturn return_type function_name(parameters)
{
/* Function body that never returns */
}
Example 1: _Noreturn with exit() Function
When a function marked with _Noreturn calls exit(), it terminates the program without returning control to the caller −
#include <stdio.h>
#include <stdlib.h>
_Noreturn void terminate_program() {
printf("Function called - terminating program<br>");
exit(0);
}
int main() {
printf("Program started<br>");
terminate_program();
printf("This line will never execute<br>");
return 0;
}
Program started Function called - terminating program
Example 2: _Noreturn with Infinite Loop
A _Noreturn function can also contain an infinite loop that never allows the function to return −
#include <stdio.h>
_Noreturn void infinite_loop() {
printf("Entering infinite loop<br>");
int count = 1;
while (1) {
printf("Loop iteration: %d<br>", count++);
if (count > 5) break; /* For demo purposes only */
}
}
int main() {
printf("Program started<br>");
infinite_loop();
printf("This line will never execute<br>");
return 0;
}
Program started Entering infinite loop Loop iteration: 1 Loop iteration: 2 Loop iteration: 3 Loop iteration: 4 Loop iteration: 5
Example 3: _Noreturn with return Statement (Warning)
Using a return statement in a _Noreturn function violates its contract and generates compiler warnings −
#include <stdio.h>
#include <stdlib.h>
_Noreturn void invalid_function() {
printf("This function should not return<br>");
return; /* This causes undefined behavior */
}
int main() {
printf("Calling invalid _Noreturn function<br>");
invalid_function();
printf("Unexpectedly returned<br>");
return 0;
}
warning: function declared 'noreturn' has a 'return' statement Calling invalid _Noreturn function This function should not return Unexpectedly returned
Key Points
-
_Noreturnis a function specifier introduced in C11 standard - It helps compilers optimize code by marking unreachable statements
- Functions marked
_Noreturnmust never return under any circumstances - Common uses include error handlers, program terminators, and infinite event loops
Conclusion
The _Noreturn function specifier is a valuable tool for indicating functions that never return control to their callers. It improves code clarity and enables compiler optimizations while helping detect unreachable code.
