Thursday, 24 January 2013

Functions setjmp( ) and longjmp( ) in C

  C language provide only limited branching facility. Most of the constructs in C provide conditional jumps only. Of course there is goto, but goto is not very powerful. Consider the program given below.

#include <stdio.h>

void fun()
{
    printf("\nYou are in the function fun\n");
    goto x;
    printf("\nyou will not see this, because of goto\n");
}
int main()
{
    printf("\nYou are in the main function\n");
    fun();
    printf("\nThis line will not be printed\n");
    x:
    printf("\nThis line will be printed\n");
    return 0;
}


The program will give you the following error "label 'x' used but not defined". The label of a goto statement is only having a function scope. Because of this limitation you can not jump out side a function using goto statement. But don't worry, we can use setjmp( ) and longjmp( ) to jump out of a function. We can also jump out of a file using these functions. These functions are defined inside the header file setjmp.h. Consider the program given below.

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

jmp_buf buf;
 

void fun()
{
    printf("\nYou are in function fun\n");
    longjmp(buf,1);
    printf("\nYou will never see this, because of longjmp");
}
int main()
{
     if(setjmp(buf))
     {
        printf("\nYou are back in main\n");
     }
     else
     {
        printf("\nYou are in main\n");
        fun();
     }
     return 0;
}

Figure shows the Output of the Program

In the program setjmp(jmp_buf j) must be called first. It says use the variable j to remember where you are now and returns 0 from the call. Function longjmp(jmp_buf j, int i) can then be called. It says go back to the place where j is set, i.e., to the location of the setjmp( ). Function longjmp( ) returns the value of variable i to the function setjmp( ).

 

No comments:

Post a Comment