【问题标题】:Data types in #define function-like macros#define 类函数宏中的数据类型
【发布时间】:2013-10-12 03:56:52
【问题描述】:

我正在尝试制作一个计算 2 n 和 2 n - 1 的宏。那将是:

#define b(n) (2 << (n))
#define a(n) ((b(n))-1)

但是由于某种原因,这将其转换为int,但我愿意使用unsigned long int。有谁知道如何解决这个问题?我曾经考虑过使用内联函数,但是我并没有完全理解类函数宏和内联函数之间的区别。

【问题讨论】:

  • 你不想#define b(n) (1u &lt;&lt; (n))
  • 把它改成#define b(n) (2ULL&lt;&lt;(n)),应该会很长
  • @Roberto ... 或(((uintmax_t)1) &lt;&lt; ((unsigned)(n)))
  • @chux: 是的,1 是对的,不是 2,你是对的 (1
  • 感谢 Brian 的编辑!

标签: c macros int c-preprocessor primitive-types


【解决方案1】:

OP 想要unsigned long int,然后在你的宏中使用那个类型

#define b(n) (1UL<<((unsigned)(n)))

当 OP 使用(2 &lt;&lt; (n)) 时,结果是类型int,因为2int。带有intunsigned 的运算符&lt;&lt; 得到int。而是始终使用unsigned


此外,为了模拟 power(2,n),OP 肯定想使用 1 左移,而不是 2 左移。

【讨论】:

  • 确实加UL解决了问题,其实我正要通知我解决了casting (unsigned long int) infront 1的问题
猜你喜欢
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多