longjmp (C++)

Was introduced to this keyword through CS343.

https://www.fmc-modeling.org/category/projects/apache/amp/A_5_Longjmp.html

what happens if i call longjmp(jumpbufer, 2)? That sets the value of jmpBuffer to 2? so then, setjmp(jumpBuffer) == 2) is true?

  • Yes
#include <iostream>
#include <csetjmp>
 
jmp_buf jumpBuffer;
 
void someFunction() {
    std::cout << "In some function. Triggering longjmp...\n";
    longjmp(jumpBuffer, 2);  // This makes setjmp return 2
}
 
int main() {
    int val = setjmp(jumpBuffer);
 
    if (val == 0) {
        std::cout << "Setjmp returned 0, normal execution.\n";
        someFunction();  // Call the function that will trigger longjmp
    } else if (val == 2) {
        std::cout << "Setjmp returned 2 after longjmp.\n";
    }
 
    std::cout << "Program continues...\n";
    return 0;
}