tags:

views:

275

answers:

4

I have read the following tutorial, but I don't understand it well. When is longjmp used and why it is necessary to know?

http://www.cplusplus.com/reference/clibrary/csetjmp/longjmp/

+14  A: 

Just don't use it.

The only time you'd want to use it in C++ is never. You should never have any reason to use it in a well-written C++ program (in fact, you should never have any reason to use it in a poorly-written C++ program).

James McNellis
+1 I've never used that function and I'm OK.
Kirill V. Lyadvinsky
I used it once, for purposes too evil to describe. I think I'm OK now.
Mike Seymour
+4  A: 

In C++, it's not used and it's not necessary to know, is the short.

DeadMG
+5  A: 

setjmp/longjmp is an old-fashioned way of handling exceptions. First, you set the jump point with setjmp(). Then later, from anywhere else in your program, you can jump back to that point with longjmp(). If your program can use exceptions -- and most programs can these days -- then you don't need to use these functions.

Hollance
You can't use `setjmp`/`longjmp` as an alternative to exception handling in C++, unless you never use classes with nontrivial destructors. They won't unwind the stack, so you'll end up leaking resources all over the place.
Mike Seymour
And strictly speaking, using it to jump out of the scope of *any* automatic variable is undefined behaviour.
Mike Seymour
+3  A: 

In a nutshell, setjmp and longjmp are a way of changing the flow of control in your program. They work something like this:

  1. You call setjmp. The function returns a token, the jmp_buf
  2. You go off and do something else.
  3. You call longjmp and pass it the token you got from setjmp. When you do, the program will return to the poinnt where you called setjmp. It doesn't matter if you're in another function. It's like a GOTO statement on steroids, with all the benefits and disadvantages something like that brings.

As a previous poster said, don't use it. You can tie yourself in knots because the flow of control in your program is moving about the place. However, setjmp/longjmp do have practical uses. For example, they can be used to simulate exceptions in C. But generally speaking, they're more trouble than they're worth!

Ken Keenan