我正在处理一些位操作,并在宏与内联函数中的同一行代码中遇到奇怪的不同输出。该函数从-th 位置返回具有L
活动位的 64 位掩码: 。有人可以告诉我输出不同的原因吗?N
(~0<<N) - (~0<<(N+L))
#include <iostream>
#include <bitset>
using namespace std;
#define ONES (~0UL)
#define MASK(from_bit, nbits) \
(ONES << (from_bit)) - (ONES << ((from_bit) + (nbits)))
inline unsigned long int mask(size_t from_bit, size_t nbits) {
return (ONES << from_bit) - (ONES << (from_bit + nbits));
}
int main(int argc, char **argv) {
cout << "using #define: " << bitset<64>(MASK(63, 3)) << endl;
cout << "using inline function: " << bitset<64>(mask(63, 3)) << endl;
return 0;
}
输出:
$ g++ -o test main.cc
main.cc: In function 'int main(int, char**)':
main.cc:15: warning: left shift count >= width of type
$ ./test
using #define: 1000000000000000000000000000000000000000000000000000000000000000
using inline function: 1000000000000000000000000000000000000000000000000000000000000100
------^
-O3
使用选项编译:
$ g++ -O3 -o test2 main2.cc
main.cc: In function 'int main(int, char**)':
main.cc:15: warning: left shift count >= width of type
$ ./test2
using #define: 1000000000000000000000000000000000000000000000000000000000000000
using inline function: 0000000000000000000000000000000000000000000000000000000000000000
------^
编译器信息:
$ g++ --version
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)