Why does this setjmp program print a 5?

174 views Asked by At

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!

3

There are 3 answers

4
Sergey Kalinichenko On BEST ANSWER

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).

2
john On

You cannot use longjmp to return to a function you have exited. In other words longjmp won't restore the stack for you. See here.

What you need is a language like scheme, where doing this kind of thing would be perfectly normal.

0
Zac Howland On

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.