你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

[C++]用throw跳转控制流程 玩得飞起

2021-12-2 3:39:41

源地址:https://twitter.com/HenryKSloan/status/1464652050260758533

#include <iostream>

int main()
{
    constexpr struct break_loop1_t {} break_loop1;
    try {
        for (int i = 0; i < 10; i++) {
            constexpr struct break_loop2_t {} break_loop2;
            try {
                for (int j = 0; j < 10; j++) {
                    for (int k = 0; k < 10; k++) {
                        std::cout << i << ' ' << j << ' ' << k << '\n';
                        if (j == 5) {
                            throw break_loop2;
                        }
                    }
                    if (i == 8) {
                        throw break_loop1;
                    }
                }
            } catch (break_loop2_t) {
            }
        }
    } catch (break_loop1_t) {
    }
}

测试:https://godbolt.org/z/n9fYqY5Yh