title: Why pointer subtraction is undefined behavior in C++?
body: <p>For the example below, what may cause <code>undefined behavior</code>? and <strong>why?</strong> </p>
  
  <pre><code>#include &lt;cstddef&gt; 
  #include &lt;iostream&gt; 
  
  template &lt;typename Ty&gt; 
  bool in_range(const Ty *test, const Ty *r, size_t n) 
  { 
      return 0 &lt; (test - r) &amp;&amp; (test - r) &lt; (std::ptrdiff_t)n; 
  }
  
  void f() { 
       double foo[10]; 
       double *x = &amp;foo[0]; 
       double bar; 
       std::cout &lt;&lt; std::boolalpha &lt;&lt; in_range(&amp;bar, x, 10);
  }
  </code></pre>
  
  <p>I have not found the answer in <a href="https://stackoverflow.com/questions/12099719/when-is-pointer-subtraction-undefined-in-c">When is pointer subtraction undefined in C?</a></p>