0

In the following code:

int main(void)
{
  jmp_buf buf;
  int x = 1;

  // Do stuff with x in a non-volatile, optimized way.

  volatile int* x_p = &x;
  switch (setjmp(buf)) {
    case 0: {
      *x_p = 3;
      longjmp(buf, 1);
    }
    case 1: {
      printf("x is %i.\n", x);        // This probably gets 3?
      printf("*x_p is %i.\n", *x_p);  // This definitely gets 3
      break;
    }
  }
}

one could imagine that using x_p to access x in the case 0 block would be sufficient to circumvent the issue with local variables and setjmp but I could imagine that the first setjmp call would actually store the value 1 in its internal register map or whatever and the direct read of x in case 1 would actually return 1. On my machine both printed values are 3 but is this necessarily the case? More generally, is using x directly in the non-0 case blocks guaranteed to return any changed values written by the case 0 block?

NOTE: Preemptively noting that this is out of curiosity and not because I need to do any of this in real code :)

Luis
  • 1,210
  • 2
  • 11
  • 24
  • According to the referenced question and its answer, the value of x, which is non-volatile, autostorage, and changed in-between the setjmp() and longjmp() calls, is indeterminate in the case-1-block. However, the pointer to x is not changed, therefore, it does not need to be declared volatile. Also, declaring x as volatile would guarantee that it holds the value as of the time longjmp() was called. – Matthias Oct 20 '17 at 19:22
  • @Matthias, the pointer is not volatile, it's pointee is. Note that I *think* the compiler has more obligations due to the address of `x` being stored, and that is the crux of the issue. – Luis Oct 20 '17 at 20:11

0 Answers0