title: C# vs C++ ternary operator
body: <p>I used to be a C++ programer on Windows.
  I know that the compiler will optimizes the ternary operator in C++.</p>
  
  <p>C++ code:</p>
  
  <pre><code>#include "stdafx.h"
  int _tmain(int argc, _TCHAR* argv[])
  {
      int result = argc &gt; 3 ? 1 : 5;
      printf("%d", result);
      return 0;
  }
  </code></pre>
  
  <p>Because of the pipeline stuff, the generated native code is shown as below (of course <strong>Release</strong> model):</p>
  
  <pre><code>int result = argc &gt; 3 ? 1 : 5;
  00B21003  xor         eax,eax  
  00B21005  cmp         dword ptr [argc],3
  00B21009  setle       al  
  00B2100C  lea         eax,[eax*4+1]
  </code></pre>
  
  <p>C# code:</p>
  
  <pre><code>namespace TernaryOperatorCSharp
  {
      static void Main(string[] args)
      {
          int argc = args.Length;
          int result = argc &gt; 1 ? 2 : 5;
          System.Console.WriteLine(result);
      }
  }
  </code></pre>
  
  <p>I looked up the native code JIT generated, but there is no optimization at all (still two jump instructions).</p>
  
  <pre><code>int result = argc &gt; 1 ? 2 : 5;
  0000002f  cmp         dword ptr [ebp-4],1 
  00000033  jg          0000003F 
  00000035  nop 
  00000036  mov         dword ptr [ebp-0Ch],5 
  0000003d  jmp         00000046 
  0000003f  mov         dword ptr [ebp-0Ch],2 
  00000046  mov         eax,dword ptr [ebp-0Ch] 
  00000049  mov         dword ptr [ebp-8],eax 
  System.Console.WriteLine(result);
  0000004c  mov         ecx,dword ptr [ebp-8] 
  0000004f  call        6A423CBC 
  </code></pre>
  
  <p>Why doesn't the C# JIT compiler make the same optimization as C++ compiler does?</p>
  
  <p>What's the story behind this?</p>
  
  <p>Any information will be appreciated.</p>
  
  <hr>
  
  <p>Hi there,
  I have modified the C# program and run it with release model.</p>
  
  <p><strong>Before</strong></p>
  
  <pre><code>int result = args.Length &gt; 1 ? 2 : 5;
  </code></pre>
  
  <p><strong>Now</strong></p>
  
  <pre><code>int argc = args.Length;
  int result = argc &gt; 1 ? 2 : 5;
  </code></pre>
  
  <p>But the result is still the same.
  There still two jump instruction exist.
  I will appreciate it if there is any further more information.</p>