title: Using C++ lambda functions during variable initialisation
body: <p>I think many of you have this kind of code somewhere:</p>
  
  <pre><code>int foo;
  switch (bar) {
    case SOMETHING: foo = 5;  break;
    case STHNELSE:  foo = 10; break;
    ...
  }
  </code></pre>
  
  <p>But this code has some drawbacks:</p>
  
  <ul>
  <li>You can easily forget a "break"</li>
  <li>The <code>foo</code> variable is not const while it should be</li>
  <li>It's just not beautiful</li>
  </ul>
  
  <p>So I started wondering if there was a way to "improve" this kind of code, and I got this little idea:</p>
  
  <pre><code>const int foo = [&amp;]() -&gt; int {
    switch (bar) {
      case SOMETHING: return 5;
      case STHNELSE:  return 10;
      ...
    }
  }();
  </code></pre>
  
  <p><em>Note: the first pair of parentheses it not mandatory, but MSVC++ doesn't support this yet</em></p>
  
  <p>You can use the same trick with if-else where the ternary operator would be too complicated, variables that require to be passed by pointers to be initialized (like for DirectX functions), etc.</p>
  
  <p>My questions are:</p>
  
  <ul>
  <li>Is there anything wrong with this code that I didn't see?</li>
  <li>Do you find it better than the one above?</li>
  <li>g++ seems to inline the function, but do you think that all compilers will do so?</li>
  </ul>
  
  <p><strong>EDIT:</strong> this is what I mean by "DirectX functions"</p>
  
  <pre><code>_xAudio2 = [&amp;]() -&gt; std::shared_ptr&lt;IXAudio2&gt; {
      IXAudio2* ptr = nullptr;
      if (FAILED(XAudio2Create(&amp;ptr, xAudioFlags, XAUDIO2_DEFAULT_PROCESSOR)))
          throw std::runtime_error("XAudio2Create failed");
      return std::shared_ptr&lt;IXAudio2&gt;(ptr, [](IUnknown* ptr) { ptr-&gt;Release(); });
  }();
  </code></pre>