title: if vs if constexpr inside constexpr function
body: <p>Recently I modify some <code>if constexpr</code> into <code>if</code> in my constexpr functions and found they still work fine and can be evaluated when compile time. Here is a minimum case:</p>
  
  <pre><code>template&lt;int N&gt;
  constexpr bool is_negative()
  {
      if constexpr  (N &gt;= 0) return false;
      else  return true; 
  }
  int main()
  {
      constexpr  bool v = is_negative&lt;1&gt;();
  }
  </code></pre>
  
  <p><a href="https://godbolt.org/z/4cv0Es" rel="nofollow noreferrer"><strong><code>live demo</code></strong></a></p>
  
  <p>In the case above, <code>N</code> must be known at compile time because it is non-type template parameter, so <code>if constexpr</code> works fine here. However, it is a constexpr function, so, iirc, it is <strong>possible</strong> to get a return value even though I replace <code>if constexpr</code> with <code>if</code>: </p>
  
  <pre><code>template&lt;int N&gt;
  constexpr bool is_negative()
  {
      if  (N &gt;= 0) return false;
      else  return true; 
  }
  int main()
  {
      constexpr  bool v = is_negative&lt;1&gt;();
  }
  </code></pre>
  
  <p><a href="https://godbolt.org/z/rcUXvS" rel="nofollow noreferrer"><strong><code>live demo</code></strong></a></p>
  
  <p>From <a href="https://en.cppreference.com/w/cpp/language/constexpr" rel="nofollow noreferrer">cppref</a>, all of the requirements in <code>A constexpr function must satisfy the following requirements:</code> don't mention <code>if</code>. So, IIUC, it should be implementation defined behavior whether constexpr function contain <code>if</code> to be evaluted at compile time even though all related variable is known at compile time(like <code>is_negative</code> above).</p>
  
  <p>So, my conclusion is: </p>
  
  <ul>
  <li>Before c++17, we don't have <code>if constexpr</code>, so the choice is <code>if</code>, which means it is not guaranteed to get our constexpr functions get evaluted at compile time, all depend on compiler implementation</li>
  <li>After c++17, <code>if constexpr</code> is preferred if we want constexpr functions get evaluated at compile time.</li>
  </ul>
  
  <p>All above is my personal thoughts, maybe something important missed/misunderstand, feel free to correct me. The question is still unchanged: <code>if</code> and <code>if constexpr</code>, which should be prefered for constexpr functions which expected to be evaluated at compile time.</p>
  
  <p>references: 
  - <a href="https://stackoverflow.com/questions/41618576/what-is-allowed-in-a-constexpr-function">What is Allowed in a constexpr Function?</a>
  - <a href="https://stackoverflow.com/questions/43434491/difference-between-if-constexpr-vs-if">Difference between &quot;if constexpr()&quot; Vs &quot;if()&quot;</a></p>