setjmp function(Prepare for Nonlocal Jump) in C Language – example and detail

In the C Programming Language, the setjmp feature shops the present day surroundings in the env variable in education for a future name from the longjmp function.

Syntax

The syntax for the setjmp feature in the C Language is:

int setjmp(jmp_buf env);

Parameters or Arguments

env The cutting-edge surroundings saved for a future longjmp function call.

Returns

The setjmp function returns zero when it is known as directly. When it is returning from a name from the longjmp function, the setjmp feature will return a nonzero value.

Required Header

In the C Language, the required header for the setjmp feature is:

#include <setjmp.h>

Applies To

In the C Language, the setjmp characteristic can be used in the following versions:

ANSI/ISO 9899-1990

setjmp Example

/* Example using setjmp by TechOnTheNet.com */

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

/* Declare a global jmp_buf variable that is available to both func and main */
static jmp_buf env;

void func(void)
{
    /* Display a message indicating we are entering func */
    printf("Starting func\n");

    /* Return to main with a return code of 1 (can be anything except 0) */
    longjmp(env, 1);

    /* Display a message indicating we are leaving func */
    printf("Finishing func\n"); /* This will never be executed! */
}

int main(int argc, const char * argv[])
{
    /* Define temporary variables */
    int result;

    /* Display a message indicating we are starting main */
    printf("Starting main\n");

    /* Save the calling environment, marking where we are in main */
    result = setjmp(env);

    /* If the result is not 0 then we have returned from a call to longjmp */
    if (result != 0)
    {
        /* Display a message indicating the call to longjmp */
        printf("longjmp was called\n");

        /* Exit main */
        return 0;
    }

    /* Call func */
    func();

    /* Display a message indicating we are leaving main */
    printf("Finished main\n");

    return 0;
}

When compiled and run, this utility will output:

Starting main
Starting func
longjmp was called

Similar Functions

Other C features that are similar to the setjmp function:

longjmp function <setjmp.h>

See Also

Other C features that are noteworthy when dealing with the setjmp function:

signal function <signal.h>