Search code examples
c++setjmp

question with longjmp


I want to use longjmp to simulate goto instruction.I have an array DS containing elements of struct types (int , float, bool ,char). I want to jump to the place labled "lablex" where x is DS[TOP].int_val. how can I handle this?

sample code :

...
jmp_buf *bfj;
...
stringstream s;s<<"label"<<DS[TOP].int_val;
bfj = (jmp_buf *) s.str();
longjmp(*bfj,1);

but as I thought it's having problem what should I do?

error:

output.cpp: In function ‘int main()’:

output.cpp:101: error: invalid cast from type ‘std::basic_string, std::allocator >’ to type ‘__jmp_buf_tag (*)[1]’


Solution

  • You probably don't want to use longjmp at all but I hate it when people answer a question with "Why would you want to do that?" As has been pointed out your longjmp() usage is wrong. Here is a simple example of how to use it correctly:

    #include <setjmp.h>
    
    #include <iostream>
    
    using namespace std;
    
    jmp_buf jumpBuffer;  // Declared globally but could also be in a class.
    
    void a(int count) {
      // . . .
      cout << "In a(" << count << ") before jump" << endl;
      // Calling longjmp() here is OK because it is above setjmp() on the call
      //   stack.
      longjmp(jumpBuffer, count);  // setjump() will return count
      // . . .
    }
    
    
    void b() {
      int count = 0;
    
      cout << "Setting jump point" << endl;
      if (setjmp(jumpBuffer) == 9) return;
      cout << "After jump point" << endl;
    
      a(count++);  // This will loop 10 times.
    }
    
    
    int main(int argc, char *argv[]) {
      b();
    
      // Note: You cannot call longjmp() here because it is below the setjmp() call
      //  on the call stack.
    
      return 0;
    }
    

    The problems with your usage of longjmp() are as follows:

    1. You don't call setjmp()
    2. You haven't allocated the jmp_buf either on the stack or dynamically. jmp_buf *bfj is just a pointer.
    3. You cannot cast a char * to jmp_buf * and expect it to work. C++ not a dynamic language it is statically compiled.

    But really, it is very unlikely that you should be using longjmp() at all.