tags:

views:

249

answers:

4

I have seen this macro defined before but never really knew its purpose. Can anyone shed light on this?

A: 

I've seen things like that before as part of testing. If it is executed, then you know that you have a bug.

Brian Knoblauch
+1  A: 

I've not seen it before, but STFW with Google comes up with this question first, and then some other references. From what it says, it is clearly a hint to the compiler that the code is never executed - so the compiler can do optimization. It could legitimately be regarded as an excuse to put 'assert(0)' in its place -- since the code will never be executed, the assertion will never fire. Of course, if the assertion does fire, then you know you've got a problem.

See also the classic paper "Can't Happen or /* NOTREACHED */ or Real Programs Dump Core".

Worth a read, even now.

Jonathan Leffler
+4  A: 

This is a compiler intrinsic used for optimization, typically seen in embedded programming. The only time I have seen it used is in the "default" for a switch statement to assert that the variable has a limited range (for better optimization). Example:

 /* Get DTMF index */
 switch(dtmf)
 {
     case '0':
     case '1':
     case '2':
     case '3':
     case '4':
     case '5':
     case '6':
     case '7':
     case '8':
     case '9':
         /* Handle numeric DTMF */
         index = dtmf - '0';
         break;
     case 'A':
     case 'B':
     case 'C':
     case 'D':
         index = dtmf - 'A' + 10;
         break:
     default:
         _never_executed();
         break;
 }

Probably doesn't work with all compilers...

JayG
+1  A: 

As an FYI, MSVC has something similar (with a bit more flexibility), the __assume() intrinsic. One example they give:

int main(int p)
{
   switch(p){
      case 1:
         func1(1);
         break;
      case 2:
         func1(-1);
         break;
      default:
         __assume(0);
            // This tells the optimizer that the default
            // cannot be reached. As so, it does not have to generate
            // the extra code to check that 'p' has a value 
            // not represented by a case arm. This makes the switch 
            // run faster.
   }
}

I'm not sure which version of MSVC this was first supported.

Michael Burr