1

Here is my experimental code:

#include <setjmp.h>
#include <stdio.h>

static jmp_buf buf;

int main() 
{
    volatile int b = 3;

    if (setjmp(buf) != 0) {
        printf("%d\n", b);
        return 0;
    }

    b = 5;
    longjmp(buf, 1);
}

My understanding of setjmp and longjmp renders the code into this:

int main() 
{
    volatile int b = 3;

    setjmp(buf);   /* the env is saved and b's value is 3 in that env */

    b = 5;

    longjmp(buf, 1);  /* the saved env is restored and b is 3, not 5 */

    printf("%d\n", b);

    return 0;
}

So, in my count, the output value is 3. But it is actually 5. Why is that?

I also tried removing volatile from b's declaration; this doesn't many any difference.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
my_question
  • 3,075
  • 2
  • 27
  • 44
  • 2
    By "environment" getting restored, I don't think it means the values of all local variables. It only means CPU registers. There's no guarantee that a variable declared `volatile` will be placed into a register. – Cody Gray - on strike Aug 17 '14 at 00:24
  • Without `volatile`, you might see a 3 - actually the behavior is undefined if you access `b` after `longjmp` when it was modified between the `setjmp` and `longjmp` - but with `volatile`, you reliably see the 5. – R.. GitHub STOP HELPING ICE Aug 17 '14 at 03:03

0 Answers0