Thread: Usage of setjmp(buf) and longjmp?

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    83

    Usage of setjmp(buf) and longjmp?

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

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    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.

    --
    Mats
    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