title: Why is the following code illegal in C++
body: <p>I want to create an <code>if</code> where a variable is declared, assigned and checked. If the variable's value is acceptable, I want to use it inside <code>if</code> body. Here's an example of how I thought I could do that:</p>
  
  <pre><code>if ((int result = Foo()) != 0) {
      // use result
  }
  </code></pre>
  
  <p>I assumed that <code>Foo()</code> returns some value, which is assigned to <code>result</code>, and returned by assignment operator <code>=</code>, and finally checked against <code>0</code> in <code>!= 0</code>. Unfortunately, it results in a compilation error:</p>
  
  <pre><code>main.cpp:31:10: error: expected primary-expression before ‘int’
  if ((int i = Foo()) != 0)
       ^                                          
  main.cpp:31:10: error: expected ‘)’ before ‘int’
  </code></pre>
  
  <p>Why is this error happening? And what ways could there be to fix it?</p>