Emulating GCC's __builtin_unreachable?

前端 未结 5 1873
春和景丽
春和景丽 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:28

    template class Unreachable_At_Line {}; 
    #define __builtin_unreachable() throw Unreachable_At_Line<__LINE__>()
    

    Edit:

    Since you want to have unreachable code to be omitted by compiler, below is the simplest way.

    #define __builtin_unreachable() { struct X {X& operator=(const X&); } x; x=x; }
    

    Compiler optimizes away x = x; instruction especially when it's unreachable. Here is the usage:

    int foo (int i)
    {
      switch(i)
      {
      case 0:  return 0;
      case 1:  return 1;
      default: return -1;
      }
      __builtin_unreachable();  // never executed; so compiler optimizes away
    }
    

    If you put __builtin_unreachable() in the beginning of foo() then compiler generates a linker error for unimplemented operator =. I ran these tests in gcc 3.4.6 (64-bit).

提交回复
热议问题