Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time bitwise operations in C/C++

I'm trying to understand how bitwise operations are handled by C/C++ compilers. Specifically, I'm talking about C compiled with gcc, but I believe that the question is a bit more general than that.

Anyway, suppose I have a macros defined as follows:

  #define SOME_CONSTANT 0x111UL
  #define SOME_OFFSET   2
  #define SOME_MASK     7
  #define SOME_VALUE    ((SOME_CONSTANT) << (SOME_OFFSET)) & (SOME_MASK)

  static inline void foo() { printf("Value: %lu#n", SOME_VALUE); }

All the ingredients of SOME_VALUE are constants, and they are all known at compile time.

So my question is: will gcc evaluate SOME_VALUE at compile time, or will it be done at runtime only? How do I check whether a gcc supports such optimization?

like image 826
kliteyn Avatar asked Apr 02 '15 07:04

kliteyn


People also ask

Are bitwise operations fast?

On simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplication, and sometimes significantly faster than addition.

What is bitwise operator in C with example?

Bitwise AND operator Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0. For example, We have two variables a and b.


1 Answers

Your compiler does not know about SOME_VALUE. The C code is first passed through the C Preprocessor to C compiler. You can see the output of the C Preprocessor by running gcc as:

gcc -E code.c

You'll see that the real code fed to C compiler is:

int main(void) {
 printf("Value: %lu#n", ((0x111UL) << (2)) & (7));
 return 0;
}

So the question becomes "Does C Compiler of GCC optimize ((0x111UL) << (2)) & (7)", and the answer is yes (as indicated by other answerers who proved it by looking at the assembly code generated).

like image 121
simurg Avatar answered Oct 06 '22 02:10

simurg