title: Why are Virtual Machines necessary?
body: <p>I was reading <a href="https://stackoverflow.com/questions/453610/javas-virtual-machine-and-clr">this question</a> to find out the differences between the Java Virtual Machine and the .NET CLR and Benji's answer got me wondering why Virtual Machines are necessary in the first place.</p>
  
  <p>From my understanding of Benji's explanation, the JIT compiler of a Virtual Machine interprets the intermediate code into the actual assembly code that runs on the CPU. The reason it has to do this is because CPUs often have different numbers of registers and according to Benji, "some registers are special-purpose, and each instruction expects its operands in different registers." This makes sense then that there is a need for an intermediary interpreter like the Virtual Machine so that the same code can be run on any CPU.</p>
  
  <p>But, if that's the case, then what I don't understand is why C or C++ code compiled into machine code is able to run on any computer as long as it is the correct OS. Why then would a C program I compiled on my Windows machine using a Pentium be able to run on my other Windows machine using an AMD?</p>
  
  <p>If C code can run on any CPU then what is the purpose of the Virtual Machine? Is it so that the same code can be run on any OS? I know Java has VM versions on pretty much any OS but is there a CLR for other OS's besides Windows?</p>
  
  <p>Or is there something else I'm missing? Does the OS do some other interpretation of assembly code it runs to adapt it to the particular CPU or something?</p>
  
  <p>I'm quite curious about how all this works, so a clear explanation would be greatly appreciated.</p>
  
  <p>Note: The reason I didn't just post my queries as comments in the JVM vs. CLR question is because I don't have enough points to post comments yet =b.</p>
  
  <p>Edit: Thanks for all the great answers! So it seems what I was missing was that although all processors have differences there is a common standardization, primarily the X86 architecture, which provides a large enough set of common features so that the C code compiled on one X86 processor will work for the most part on another X86 processor. This furthers the justification for Virtual Machines, not to mention I forgot about the importance of garbage collection.</p>