title: Is dividing by zero accompanied with a runtime error ever useful in C++?
body: <p>According to C++ Standard (5/5) dividing by zero is undefined behavior. Now consider this code (lots of useless statements are there to prevent the compiler from optimizing code out):</p>
  
  <pre><code>int main()
  {
      char buffer[1] = {};
      int len = strlen( buffer );
      if( len / 0 ) {
          rand();
      }
  }
  </code></pre>
  
  <p>Visual C++ compiles the <code>if</code>-statement like this:</p>
  
  <pre><code>sub         eax,edx 
  cdq 
  xor         ecx,ecx 
  idiv        eax,ecx 
  test        eax,eax 
  je          wmain+2Ah (40102Ah) 
  call        rand
  </code></pre>
  
  <p>Clearly the compiler sees that the code is to divide by zero - it uses <code>xor x,x</code> pattern to zero out <code>ecx</code> which then serves the second operand in integer division. This code will definitely trigger an "integer division by zero" error at runtime.</p>
  
  <p>IMO such cases (when the compiler knows that the code will divide by zero at all times) are worth a compile-time error - the Standard doesn't prohibit that. That would help diagnose such cases at compile time instead of at runtime.</p>
  
  <p>However I talked to several other developers and they seem to disagree - their objection is "what if the author wanted to divide by zero to... emm... test error handling?"</p>
  
  <p>Intentionally dividing by zero without compiler awareness is not that hard - using <code>__declspec(noinline)</code> Visual C++ specific function decorator:</p>
  
  <pre><code>__declspec(noinline)
  void divide( int what, int byWhat )
  {
      if( what/byWhat ) {
         rand();
      }
  }
  
  void divideByZero()
  {
      divide( 0, 0 );
  }
  </code></pre>
  
  <p>which is much more readable and maintainable. One can use that function when he "needs to test error handling" and have a nice compile-time error in all other cases.</p>
  
  <p>Am I missing something? Is it necessary to allow emission of code that the compiler knows divides by zero?</p>