title: Why does the ternary operator with commas evaluate only one expression in the true case?
body: <p>I'm currently learning C++ with the book C++ Primer and one of the exercises in the book is:</p>
  
  <blockquote>
    <p>Explain what the following expression does: <code>someValue ? ++x, ++y : --x, --y</code></p>
  </blockquote>
  
  <p>What do we know? We know that the ternary operator has a higher precedence than the comma operator. With binary operators this was quite easy to understand, but with the ternary operator I am struggling a bit. With binary operators "having higher precedence" means that we can use parentheses around the expression with higher precedence and it will not change the execution.</p>
  
  <p>For the ternary operator I would do:</p>
  
  <pre><code>(someValue ? ++x, ++y : --x, --y)
  </code></pre>
  
  <p>effectively resulting in the same code which does not help me in understanding how the compiler will group the code.</p>
  
  <p>However, from testing with a C++ compiler I know that the expression compiles and I do not know what a <code>:</code> operator could stand for by itself. So the compiler seems to interpret the ternary operator correctly.</p>
  
  <p>Then I executed the program in two ways:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  int main()
  {
      bool someValue = true;
      int x = 10, y = 10;
  
      someValue ? ++x, ++y : --x, --y;
  
      std::cout &lt;&lt; x &lt;&lt; " " &lt;&lt; y &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  
  <p>Results in:</p>
  
  <pre><code>11 10
  </code></pre>
  
  <p>While on the other hand with <code>someValue = false</code> it prints:</p>
  
  <pre><code>9 9
  </code></pre>
  
  <p>Why would the C++ compiler generate code that for the true-branch of the ternary operator only increments <code>x</code>, while for the false-branch of the ternary it decrements both <code>x</code> and <code>y</code>?</p>
  
  <p>I even went as far as putting parentheses around the true-branch like this:</p>
  
  <pre><code>someValue ? (++x, ++y) : --x, --y;
  </code></pre>
  
  <p>but it still results in <code>11 10</code>.</p>