如何确保在编译时没有执行路径到达某一行

时间:2015-05-19 15:03:32

标签: c++

假设我在函数中有一行代码,并且我不希望有任何可以到达它的执行路径。 我可以放置一个断言(假),但我宁愿让编译器为我检查。 有任何想法吗?

示例:

请考虑以下代码(请不要评论使用goto,这不是重点。)

    // Code block starts withsome branching code.
    // By the end of this branching code, we MUST goto one of the labels below.
    // Not jumping to one of the labels is invalid, and I want to prevent 
    // that from happenning (this can be checked at compile time).

    if (...) {
        if (...) {
            goto labelA;
        }
        // The lack of a goto here is a fallthrough bug case which should not happen.
    } else if (...) {
        goto labelB;
    } else {
        goto labelC;
    }

    // -------------------- this point should not be reached. -----------------------------

labelA:
    ...
    goto final;
labelB:
    ...
    goto final;
labelC:
    ...
    goto final;
labelD:
    ...
    goto final;
final:
    return status;

2 个答案:

答案 0 :(得分:1)

你不能。

重构代码以使用现代流控制结构和函数调用。

答案 1 :(得分:0)

如@ saarraz1所述,您可能滥用goto函数而不返回void

int foo(int i)
{
    int res = 0;
    if (i % 2) {
        if (i % 3) {
            goto labelA;
        }
        // The lack of a goto here is a fallthrough bug case which should not happen.
    } else if (i % 3) {
        goto labelB;
    } else {
        goto labelC;
    }

    goto labelNoReturn; // -- this point should not be reached. --

labelA:
    res = 1;
    goto final;
labelB:
    res = 2;
    goto final;
labelC:
    res = 3;
    goto final;
final:
    return res;
labelNoReturn:
    {} 
}

发出类似于

的警告
main.cpp:33:1: warning: control reaches end of non-void function [-Wreturn-type]

Live Demo