]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/doc/gcc/extensions-to-the-c-language-family/nonlocal-gotos.rst
sphinx: add missing trailing newline
[thirdparty/gcc.git] / gcc / doc / gcc / extensions-to-the-c-language-family / nonlocal-gotos.rst
1 ..
2 Copyright 1988-2022 Free Software Foundation, Inc.
3 This is part of the GCC manual.
4 For copying conditions, see the copyright.rst file.
5
6 .. index:: nonlocal gotos
7
8 .. _nonlocal-gotos:
9
10 Nonlocal Gotos
11 **************
12
13 GCC provides the built-in functions ``__builtin_setjmp`` and
14 ``__builtin_longjmp`` which are similar to, but not interchangeable
15 with, the C library functions ``setjmp`` and ``longjmp``.
16 The built-in versions are used internally by GCC's libraries
17 to implement exception handling on some targets. You should use the
18 standard C library functions declared in ``<setjmp.h>`` in user code
19 instead of the builtins.
20
21 The built-in versions of these functions use GCC's normal
22 mechanisms to save and restore registers using the stack on function
23 entry and exit. The jump buffer argument :samp:`{buf}` holds only the
24 information needed to restore the stack frame, rather than the entire
25 set of saved register values.
26
27 An important caveat is that GCC arranges to save and restore only
28 those registers known to the specific architecture variant being
29 compiled for. This can make ``__builtin_setjmp`` and
30 ``__builtin_longjmp`` more efficient than their library
31 counterparts in some cases, but it can also cause incorrect and
32 mysterious behavior when mixing with code that uses the full register
33 set.
34
35 You should declare the jump buffer argument :samp:`{buf}` to the
36 built-in functions as:
37
38 .. code-block:: c++
39
40 #include <stdint.h>
41 intptr_t buf[5];
42
43 .. function:: int __builtin_setjmp (intptr_t *buf)
44
45 This function saves the current stack context in :samp:`{buf}`.
46 ``__builtin_setjmp`` returns 0 when returning directly,
47 and 1 when returning from ``__builtin_longjmp`` using the same
48 :samp:`{buf}`.
49
50 .. function:: void __builtin_longjmp (intptr_t *buf, int val)
51
52 This function restores the stack context in :samp:`{buf}`,
53 saved by a previous call to ``__builtin_setjmp``. After
54 ``__builtin_longjmp`` is finished, the program resumes execution as
55 if the matching ``__builtin_setjmp`` returns the value :samp:`{val}`,
56 which must be 1.
57
58 Because ``__builtin_longjmp`` depends on the function return
59 mechanism to restore the stack context, it cannot be called
60 from the same function calling ``__builtin_setjmp`` to
61 initialize :samp:`{buf}`. It can only be called from a function called
62 (directly or indirectly) from the function calling ``__builtin_setjmp``.