名稱空間
變體
操作

setjmp

來自 cppreference.com
 
 
 
 
定義於標頭檔案 <csetjmp>
#define setjmp(env) /* implementation-defined */

將當前執行上下文儲存到 env 變數中,該變數的型別為 std::jmp_buf。之後可以由 std::longjmp 函式使用此變數來恢復當前執行上下文。也就是說,當呼叫 std::longjmp 函式時,執行將在構造傳遞給 std::longjmpstd::jmp_buf 變數的特定呼叫站點處繼續。在這種情況下,`setjmp` 返回傳遞給 std::longjmp 的值。

對 `setjmp` 的呼叫必須僅出現在以下上下文中:

  1. ifswitchwhiledo-whilefor 的整個控制表示式。
    switch (setjmp(env)) { // ...
  2. 關係運算符或相等運算子的一個運算元,另一個運算元為整數常量表達式,並且結果表示式是 ifswitchwhiledo-whilefor 的整個控制表示式。
    if (setjmp(env) > 0) { // ...
  3. 一元 `!` 運算子的運算元,並且結果表示式是 ifswitchwhiledo-whilefor 的整個控制表示式。
    while (!setjmp(env)) { // ...
  4. 表示式語句的整個表示式(可能被轉換為 void)。
    setjmp(env);

如果 `setjmp` 出現在任何其他上下文中,則行為未定義。

此外,如果在 協程中 `co_await` 運算子可能使用的位置呼叫 `setjmp`,則行為未定義。

(C++20 起)

在返回到 `setjmp` 的作用域後

  • 所有可訪問物件、浮點狀態標誌和抽象機器的其他元件都具有與執行 std::longjmp 時相同的值,
  • 除了包含 `setjmp` 呼叫的函式中的非volatile區域性變數,如果它們自 `setjmp` 呼叫以來已被更改,則它們的值是不確定的。

目錄

[編輯] 引數

env - 用於儲存程式執行狀態的變數

[編輯] 返回值

如果宏由原始程式碼呼叫並且執行上下文已儲存到 env,則為 0

如果剛剛執行了非區域性跳轉,則為非零值。返回值與傳遞給 std::longjmp 的值相同。

[編輯] 注意

上述要求禁止在資料流中使用 `setjmp` 的返回值(例如,用它初始化或賦值物件)。返回值只能用於控制流或被丟棄。

[編輯] 示例

#include <array>
#include <cmath>
#include <csetjmp>
#include <cstdlib>
#include <format>
#include <iostream>
 
std::jmp_buf solver_error_handler;
 
std::array<double, 2> solve_quadratic_equation(double a, double b, double c)
{
    const double discriminant = b * b - 4.0 * a * c;
    if (discriminant < 0)
        std::longjmp(solver_error_handler, true); // Go to error handler
 
    const double delta = std::sqrt(discriminant) / (2.0 * a);
    const double argmin = -b / (2.0 * a);
    return {argmin - delta, argmin + delta};
}
 
void show_quadratic_equation_solution(double a, double b, double c)
{
    std::cout << std::format("Solving {}x² + {}x + {} = 0...\n", a, b, c);
    auto [x_0, x_1] = solve_quadratic_equation(a, b, c);
    std::cout << std::format("x₁ = {}, x₂ = {}\n\n", x_0, x_1);
}
 
int main()
{
    if (setjmp(solver_error_handler))
    {
        // Error handler for solver
        std::cout << "No real solution\n";
        return EXIT_FAILURE;
    }
 
    for (auto [a, b, c] : {std::array{1, -3, 2}, {2, -3, -2}, {1, 2, 3}})
        show_quadratic_equation_solution(a, b, c);
 
    return EXIT_SUCCESS;
}

輸出

Solving 1x² + -3x + 2 = 0...
x₁ = 1, x₂ = 2
 
Solving 2x² + -3x + -2 = 0...
x₁ = -0.5, x₂ = 2
 
Solving 1x² + 2x + 3 = 0...
No real solution

[編輯] 參閱

跳轉到指定位置
(函式) [編輯]
setjmpC 文件