totn C Functions

C Language: longjmp function
(Nonlocal Jump)

In the C Programming Language, the longjmp function restores the environment (as stored in the env variable) and returns from the original setjmp function call that saved env.

Syntax

The syntax for the longjmp function in the C Language is:

void longjmp(jmp_buf env, int val);

Parameters or Arguments

env
The environment saved by the original setjmp function call.
val
The return value for the setjmp function call.

Returns

The longjmp function does not return anything.

However, the longjmp function does affect the setjmp function return value. If val is 0, the setjmp function will return 1. Otherwise if val is a nonzero value, the setjmp function will return the setjmp return value.

Required Header

In the C Language, the required header for the longjmp function is:

#include <setjmp.h>

Applies To

In the C Language, the longjmp function can be used in the following versions:

  • ANSI/ISO 9899-1990

longjmp Example

/* Example using longjmp 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 application will output:

Starting main
Starting func
longjmp was called

Similar Functions

Other C functions that are similar to the longjmp function:

See Also

Other C functions that are noteworthy when dealing with the longjmp function: