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
setjump() and longjump() in C
In this section, we will see what are the setjmp() and longjmp() functions in C. The setjmp() and longjmp() functions are located in the setjmp.h library and provide a way to perform non-local jumps in C programs.
Syntax
#include <setjmp.h> int setjmp(jmp_buf env); void longjmp(jmp_buf env, int val);
Parameters
- env − A buffer of type jmp_buf that stores the calling environment
- val − An integer value to be returned by setjmp() when longjmp() is called
Return Value
- setjmp() − Returns 0 when called directly, or the value specified in longjmp() when returning from a jump
- longjmp() − Does not return; transfers control to the setjmp() call point
How It Works
These functions are used in C for exception handling. The setjmp() can be used as a try block, and longjmp() can be used as a throw statement. The longjmp() transfers control to the point which is set by setjmp().
Example: Printing Without Loops
Here we will see how to print a number 100 times without using recursion, loop, or macro expansion using setjmp() and longjmp() functions −
#include <stdio.h>
#include <setjmp.h>
jmp_buf buf;
int main() {
int x = 1;
setjmp(buf); // Set the jump position using buf
printf("5"); // Prints a number
x++;
if (x <= 100)
longjmp(buf, 1); // Jump to the point located by setjmp
printf("<br>");
return 0;
}
5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555
Example: Error Handling
A more practical example showing error handling using setjmp() and longjmp() −
#include <stdio.h>
#include <setjmp.h>
jmp_buf error_buf;
void divide(int a, int b) {
if (b == 0) {
printf("Error: Division by zero!<br>");
longjmp(error_buf, 1); // Jump back with error code
}
printf("Result: %d / %d = %d<br>", a, b, a/b);
}
int main() {
if (setjmp(error_buf) == 0) {
printf("Attempting division...<br>");
divide(10, 2); // Valid division
divide(10, 0); // This will cause a jump
printf("This line will not execute<br>");
} else {
printf("Caught error and recovered<br>");
}
return 0;
}
Attempting division... Result: 10 / 2 = 5 Error: Division by zero! Caught error and recovered
Key Points
- setjmp() saves the current execution context in the jmp_buf
- longjmp() restores the saved context and transfers control
- Use with caution as it can make code difficult to understand and debug
- Variables declared after setjmp() may have unpredictable values after longjmp()
Conclusion
The setjmp() and longjmp() functions provide a mechanism for non-local jumps in C, useful for error handling and exceptional situations. However, they should be used sparingly as they can make code flow difficult to follow.
