Reputation: 641
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!
Upvotes: 3
Views: 167
Reputation: 15870
It appears whatever compiler you are using is using a strict interpretation of what setjmp
and longjmp
do:
This macro may return more than once: A first time, on its direct invocation; In this case it always returns zero. When longjmp is called with the information set to env, the macro returns again; this time it returns the value passed to longjmp as second argument if this is different from zero, or 1 if it is zero.
From here
As it is UB, it can do this, order a pizza, end the world ... anything would be valid.
Upvotes: 0
Reputation: 726809
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 ofsetjmp()
in the same thread, with the correspondingjmp_buf
argument. If there is no such invocation, or if the function containing the invocation ofsetjmp()
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).
Upvotes: 3