Emulating GCC's __builtin_unreachable?

前端 未结 5 1863
春和景丽
春和景丽 2020-12-24 13:18

I get a whole lot of warnings about switches that only partially covers the range of an enumeration switched over. Therefor, I would like to have a \"default\" for

5条回答
  •  孤城傲影
    2020-12-24 13:41

    You can call an inline function declared _Noreturn to mark anything after that call as unreachable. The compiler is allowed to throw out any code after such a function. If the function itself is static (and does return), the compiler will usually also inline the function. Here is an example:

    static _Noreturn void unreachable() {
        return; /* intentional */
    }
    
    /* ... */
    
    foo();
    bar(); /* should better not return */
    unreachable();
    baz(); /* compiler will know this is not reachable */
    

    Notice that you invoke undefined behavior if a function marked _Noreturn indeed returns. Be sure that said function will never be called.

提交回复
热议问题