gcc - C/C++编译器(例如GCC)是否通常以2的幂次幂来优化模数?

标签 gcc constants compiler-optimization modulo compile-time-constant

假设我有类似的东西:

#define SIZE 32

/* ... */

unsigned x;

/* ... */

x %= SIZE;


大多数C / C ++编译器(例如GCC)通常会将x % 32减小为x & 31吗?

最佳答案

是的,任何受人尊敬的编译器都应执行此优化。具体来说,其中% X是2的恒定幂的X操作将等同于& (X-1)操作。

GCC甚至会在关闭优化的情况下执行此操作:

示例(Cygwin上的gcc -c -O0版本3.4.4):

unsigned int test(unsigned int a) {
   return a % 32;
}


结果(objdump -d):

00000000 <_test>:
   0:   55                      push   %ebp
   1:   89 e5                   mov    %esp,%ebp
   3:   8b 45 08                mov    0x8(%ebp),%eax
   6:   5d                      pop    %ebp
   7:   83 e0 1f                and    $0x1f,%eax          ;; Here
   a:   c3                      ret

关于gcc - C/C++编译器(例如GCC)是否通常以2的幂次幂来优化模数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22446425/

相关文章:

c++ - const 右值引用是否允许对编译器进行额外优化?

c++ - C++ 运算符重载返回中的常量正确性

c++ - const 参数不够 const

asp.net - web.config中system.codedom中多个编译器定义的影响

c++ - 有什么方法可以将 unique_ptr 插入到 C++0x/gcc 4.4.7 中的映射中)?

const char * 与 == 比较

c++ - 在 C++ 中使用 std::vector 进行逃逸分析

c - Linux 上 C 语言的原子操作

c++ - ISR 中使用的指针指向寄存器

c - 使用ld链接时, undefined reference '__main'