我正在尝试制作一个计算 2 n 和 2 n - 1 的宏。那将是:
#define b(n) (2 << (n))
#define a(n) ((b(n))-1)
但是由于某些原因,这将它转换为 int
,但我愿意使用 unsigned long int
。有谁知道如何解决这个问题?我考虑过使用内联函数,但是我没有完全理解类函数宏和内联函数之间的区别。
最佳答案
OP 想要 unsigned long int
,然后在您的宏中使用该类型
#define b(n) (1UL<<((unsigned)(n)))
当 OP 使用时 (2 << (n))
,结果类型为 int
, 作为 2
是一个 int
.接线员<<
用int
和 unsigned
结果 int
.而是使用 unsigned
贯穿始终。
进一步,模拟power(2,n)
,当然 OP 想使用 1
向左移动,而不是 2
向左移动。
关于c - #define 类函数宏中的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19330361/