title: Weird behavior of & operator in C
body: <p>As part of a puzzle I am asked to implement a function which checks if two ints can be added together without overflow. Legal ops: ! ~ &amp; ^ | + &lt;&lt; >>.</p>
  
  <p>For example for x = 0x80000000 and y = 0x80000000 the function should return 0 since it is overflowing but for x = 0x80000000 and y = 0x70000000 the result would be 1.</p>
  
  <p>My solution so far is:</p>
  
  <pre><code>int addOK(int x, int y) {
      int mask = ~(1 &lt;&lt; 31);        // 0x7fffffff
      int newX = (mask &amp; (x &gt;&gt; 1)); // Shift 1 to the right to make space for overflow bit
      int newY = (mask &amp; (y &gt;&gt; 1));
      int add = newX + newY;        // Add shifted x and y - overflow bit will be the MSB
      int res = (add &amp; ~mask);      // Set all bits to 0 except MSB - MSB 1 iff overflow 0 otherwise
      int endRes = !res;            // 0x80000000 -&gt; 0x00000000, 0x00000000 -&gt; 0x00000001
      printf("mask %x newX %x newY %x add %x ~mask %x res %x endRes %x\n",mask, newX, newY, add, ~mask, res, endRes);
      return endRes;
  }
  </code></pre>
  
  <p>The function prints the following for x = 0x80000000 and y = 0x80000000:</p>
  
  <pre><code>mask 7fffffff newX 40000000 newY 40000000 add 80000000 ~mask 80000000 res 0 endRes 1
  </code></pre>
  
  <p>Now my question is why is <code>res</code> 0? it should be 0x80000000 because both <code>add</code> and <code>~mask</code> are 0x80000000. Can anyone explain this behavior to me?</p>