title: Difference in execution of left-shift between literal constant and variable with same value
body: <p>I am writing a C function which takes a parameter n and returns an int with bit representation of n 1's followed by enough 0's to fill the datatype (32 bits total). My code currently looks like this: </p>
  
  <pre><code>int upperBits(int n) {
      int retval = 0 - 1;
      int shift = 32 - n;
      retval = retval &lt;&lt; shift;
      return retval;
  }
  </code></pre>
  
  <p>This code fails when n=0, giving a return value of -1, represented by 32 1's, instead of 0. When, however, I replace shift with a literal:</p>
  
  <pre><code>int upperBits(int n) {
      int retval = 0 - 1;
      int shift = 32 - n;
      retval = retval &lt;&lt; 32;
      return retval;
  }
  </code></pre>
  
  <p>The code works properly, returning 0. I have used print statements to verify that shift = 32 when the function is called with n = 0, so I do not understand why these behave differently. What causes this difference, and how can I circumvent it?</p>
  
  <p>If it is relevant, the code is running on a Linux machine and is compiled with gcc. I am required to use straightline code with only these operators: <code>!</code> <code>˜</code> <code>&amp;</code> <code>ˆ</code> <code>|</code> <code>+</code> <code>&lt;&lt;</code> <code>&gt;&gt;</code></p>
  
  <p>EDIT: 
  I still do not know exactly what the problem is, or an elegant solution, but this workaround is effective:</p>
  
  <pre><code>int upperBits(int n) {
          int retval = 0 - 1;
          int shift = 32 - n;
          int isnull = !(n);
          printf ("%x %x %x \n", retval, shift, n);
          retval = retval &lt;&lt; (shift - isnull);
          retval = retval &lt;&lt; isnull;
          printf ("%x %x %x \n", retval, shift, n);
          return retval;
  }
  </code></pre>