Thread: Usage of setjmp(buf) and longjmp?

  1. #1
    Registered User
    Join Date
    Apr 2008

    Usage of setjmp(buf) and longjmp?

    Dear All,
    First time i read above two functions. what is the function of those two?
    int main()  
     volatile  int b;    
     int a;
     b =3;
     a = 3; 
          printf("A = %d ", a);        
          printf("\n\nB = %d ", b);        
      b = 5;
      a = 5;    
     longjmp(buf , 1);  
     return 0;

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    To jump in the code. It's pretty pointless in this example, since it's within a function, and we may just as well use some of the more common control-flow terms, e.g. do-while, while, if, goto.

    It is very useful to get back to a lower level of call-stack when something has gone horribly wrong - e.g. do setjmp() somewhere, and longjmp when an error occurs. It also works for signal handling in Linux/Unix. [Early versions of try/catch in C++ tended to use setjmp/longjmp, but nowadays, it is generally done via direct code generation in the compiler].

    It is a very BAD pair of functions, since it's goto but 3 times worse, since it can "goto" out of the current function.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed