views:

575

answers:

1

According to the C / C++ standard (see this link), the >> operator in C and C++ is not necessarily an arithmetic shift for signed numbers. It is up to the compiler implementation whether 0's (logical) or the sign bit (arithmetic) are shifted in as bits are shifted to the right.

Will this code function to ASSERT (fail) at compile time for compilers that implement a logical right shift for signed integers ?

#define COMPILE_TIME_ASSERT(EXP) \
    typedef int CompileTimeAssertType##__LINE__[(EXP) ? 1 : -1]

#define RIGHT_SHIFT_IS_ARITHMETIC \
    ( (((signed int)-1)>>1) == ((signed int)-1) )

// SHR must be arithmetic to use this code
COMPILE_TIME_ASSERT( RIGHT_SHIFT_IS_ARITHMETIC );
+4  A: 

Looks good to me! You can also set the compiler to emit an assembly file (or load the compiled program in the debugger) and look at which opcode it emits for signed int i; i >> 1;, but that's not automatic like your solution.

If you ever find a compiler that does not implement arithmetic right shift of a signed number, I'd like to hear about it.

Crashworks
Yeah, I basically want it automatic... looking at the opcodes is not reasonable expectation for this requirement because I am using it in a library that other teams may use on various platforms.
Adisak