Home » C programs

longjmp() function of setjmp.h in C

In this article we are going to learn about the longjmp() function of setjmp.h header file in C programming language and use it to restores the environment and returns from the original setjmp function.
Submitted by Abhishek Sharma, on April 20, 2018

We can call this function as an advance version of goto statement but with more dynamic range. The longjump() function allows us to pass parameters to know that the control has been jumped or not.

So how to use this is the question. First thing is to decide point from where you want to jump and then decide to where you want to jump.

Before setting these point just make a jum_buf object. Now rest is a cake walk. In this example, I have put the point from where we want to jump inside a function called func by calling the function longjmp(a, 1) with two parameters as the jum_buf object and 1 will be return at the setjump call.

Call the function setjmp() at the point to where you want to jump. The Second parameter from the longjump will be stored in z. This z can be then checked for loops or maybe something else.

setjmp.h- longjmp() function Example in C

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

//defining the type of the variable
static jmp_buf a;

void func(void)
	//message for user
	printf("Function starts here..\n");

	//calling function
	longjmp(a, 1);

	//message for user
	printf("Function ends here..\n");

int main()
	int z;

	//message for user
	printf("Main starts here..\n");

	//setting current value in z
	z = setjmp(a);

	//condition to display message
	if (z != 0)
		//message for user
		printf("longjmp function called\n");
		return 0;

	//message for user
	printf("Main ends here..\n");

	return 0;


setjmp.h - longjmp() in c language

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.