ccompilationbit-shift

Does a/the C compiler carry out shift operations at compile time?


It was mentioned that a well written compiler for C should carry out the shift opeators at compile time (i.e. not run-time); for example in this code the shift left - <<. Can anyone attest to the validity of this?

Code:

constant unsigned int elements = length/8 + (length % y > 0 ? 1 : 0);  
unsigned char bit_arr[elements];

Psuedo-Code :

bit_arr[i] |= (1 << j); // Set 
bit_arr[i] &= ~(1 << j);  // Unset
if( bit_arr[i] & (1 << j) ) // Test

Solution

  • What are you actually asking? Do you mean "will the compiler do the shift itself"? If that's what you're asking the answer is "it depends" :). If the number being shifted and the size of the shift are both compile-time constants the compiler almost surely will do the shift (though it doesn't have to). Otherwise it will generate the lower-level code that will carry out the shift (which will often be a single machine instruction).