title: Checking Enum variable for invalid value in c++
body: <p>Consider the following code.</p>
  <pre><code>//We use c++ version 98.
  
  #include &lt;iostream&gt;
  
  using namespace std;
  
  //declaration of this enum type is in C header file.
  typedef enum Color {
      Red=1, 
      Blue=11
  } Color;
  
  //Signature of this function can't be changed
  int func(Color c){
      //Following line causes UndefinedBehaviour in clang++ if 
      //value is not a valid Color value
      return (int)c;
  }
  
  int main(){
      int x;
      cin &gt;&gt; x;
      cout &lt;&lt; func((Color)x) &lt;&lt; endl;
      return 0;
  }
  
  //Compilation:
  //clang++ -fsanitize=undefined main.cpp
  </code></pre>
  <p>Now we want to check if value of <code>c</code> in <code>func</code> is valid and also want to avoid &quot;Undefined behaviour&quot;. But we do not have any control over the caller of the <code>func</code>.</p>
  <p><strong>Note</strong> that the declaration of <code>Color</code> is in <code>C</code> header file.</p>