title: Understanding sign and overflow flag in assembly
body: <p>This question is about the <code>cmp</code> instruction in assembly. I cannot understand how my books reasoning regarding the <code>SF</code> and <code>OF</code> flags.   </p>
  
  <pre><code> cmp vleft, vright
  </code></pre>
  
  <p>According to my book: For signed integers, there are three flags that are important: the zero <code>(ZF)</code> flag, the overflow <code>(OF)</code> flag and the sign <code>(SF)</code> flag. The overflow flag is set if the result of an operation overflows (or underflows). The sign flag is set if the result of an operation is negative. If <code>vleft = vright</code>, the <code>ZF</code> is set (just as for unsigned integers). If <code>vleft &gt; vright</code>, <code>ZF</code> is unset and <code>SF = OF</code>. If <code>vleft &lt; vright</code>, <code>ZF</code> is unset and <code>SF != OF</code>. Do not forget that other instructions can also change the FLAGS register, not just <code>CMP</code>.</p>
  
  <p>First, let's consider the <code>vleft &gt; vright</code> case. My book says the following:</p>
  
  <blockquote>
    <p><em>Why does SF = OF if vleft > vright? If there is no overflow, then the difference will have the correct value and must be non-negative. Thus,
    SF = OF = 0. However, if there is an overflow, the difference will not
    have the correct value (and in fact will be negative). Thus, SF = OF =
    1.</em></p>
  </blockquote>
  
  <p>The first part i understand that <code>SF = OF = 0</code>. It could for example be: </p>
  
  <p><code>0111 - 0101 = 0111 + 1010 + 1 = 10010 = 7 - 5 = 2</code> </p>
  
  <p>This would not set the <code>OF</code> or <code>SF</code> flag.</p>
  
  <p>The case could also be:</p>
  
  <p><code>1100 - 0101 = 1100 + 1010 + 1 = 10111 = -4 - 5 = 7 (-9 if we had more bits)</code> </p>
  
  <p>This would not set the <code>SF</code> flag (since the answer is the positive 7) but would set <code>OF = 1</code>, thus <code>SF != OF</code>. This clearly goes against the explanation of my book which says they should be equal.</p>
  
  <p>What am I missing here?</p>
  
  <p>Thank you!</p>