c - #define 类函数宏中的数据类型

标签 c macros int c-preprocessor primitive-types

我正在尝试制作一个计算 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 .接线员<<intunsigned结果 int .而是使用 unsigned贯穿始终。


进一步,模拟power(2,n) ,当然 OP 想使用 1向左移动,而不是 2向左移动。

关于c - #define 类函数宏中的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19330361/

相关文章:

c++ - Visual Studio 2013 中的 C,为什么以前执行的代码现在在注释中仍在执行?

c - 根据输入创建变量

c - 没有if的if语句?

c++ - 将命名空间声明为宏 - C++

c - #define func(x, y) x + y/x

c - 为什么使用 L 或 UL 等终止常量

c - 带有新参数的宏

python - 在将这个元组转换为 int 之前,我是否必须将其转换为列表?

swift - Int with no value(将 int 设置为无值)

java - 设置 int 值会导致性能问题