Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this setjmp program print a 5?

Tags:

c++

setjmp

The following code just ends up printing "5"

#include <iostream>
#include <setjmp.h>

static jmp_buf buf;

float funcB()
{
    setjmp(buf);
    return 1.6f;
}

int funcA()
{
    longjmp(buf,5);
    std::cout<<"b";
    return 2;
}

int main()
{
    funcB();
    std::cout<<funcA();
}

But this doesn't make any sense, as setjmp is returning 5, not either function... Don't worry, I'm not using this code anywhere, I'm just curious!

like image 686
foips Avatar asked Jul 08 '26 07:07

foips


1 Answers

What you are trying to do is specifically designated as undefined behavior in the documentation:

The longjmp() function restores the environment saved by the most recent invocation of setjmp() in the same thread, with the corresponding jmp_buf argument. If there is no such invocation, or if the function containing the invocation of setjmp() has terminated execution in the interim, the behaviour is undefined.

Since the function that called setjmp (i.e. funcB) has exited before you call longjmp in funcA, the behavior is undefined (it crashes on ideone).

like image 81
Sergey Kalinichenko Avatar answered Jul 13 '26 15:07

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!