内容纲要

If you know how the standard C functions setjmp() and longjmp() work, feel free to skip this short section.
I describe them here because many programmers might not be familiar with them.
The book The C Programming Language by Kernigan and Ritchie states:
“The declarations in provide a way to avoid the normal function call
and return sequence, typically to permit an immediate return from a deeply nested
function call”.

The mechanism works this way: somewhere in your code you do the following:

[cpp]
jmp_buf env;
int retval = setjmp(env)
[/cpp]

Both the function and the jmp_buf type are defined in setjmp.h .
The funny thing, and what is a source of confusion, is that setjump() returns in two different ways! The
first time when it is invoked directly as shown above, and the second time when you execute:

[cpp]
int val = a_non_zero_number ;
longjmp(env, val);
[/cpp]

Yes, you understood correctly: you invoke longjmp() and the program resumes execution after the
original invocation of setjmp() . But while when invoked directly setjmp() always returns 0 , when it returns
as a result of you executing longjmp() with the same env , it returns the value of val . This lets you neatly
distinguish between the two returns:

[cpp]
imp_buf env;
if (setjmp(env) == 0) {
// The first time setjmp() returns here
} else if (setjmp(env) == 1) {
// setjump() returns here if you execute longjmp(env, 1)
} else {
// setjump() returns here if you execute longjmp(env, n) with n greater than 1
}
[/cpp]

Obviously, besides executing longjmp() in different places with different values, you can also set more
than one jump environment.

You will see later in this chapter how to use the setjmp() / longjmp() mechanism to catch exceptions.

发表评论

电子邮件地址不会被公开。 必填项已用*标注