【问题标题】:What is wrong with the following macro usage?以下宏用法有什么问题?
【发布时间】:2013-10-14 08:12:01
【问题描述】:

isPowerof(2) in main() 导致 预期);错误 ...这有什么问题?

#include<stdio.h>

#define isPowerof2(n)  (!(n & (n-1))

int main(){
    int n,p;
    clrscr();
    printf("\nEnter the number to be Checked:");
    scanf("%d",&n);
    isPowerof2(n);
    printf("%d",p);

getch();
}

【问题讨论】:

  • 顺便提一下,isPowerof2 中的表达式将表明零是 2 的幂,这是不正确的。

标签: c syntax macros compiler-errors


【解决方案1】:

你又少了一个括号:

#define isPowerof2(n)  (!(n & (n-1)))
                                    ^

旁注:如果您不必使用宏,请改用函数。

【讨论】:

    【解决方案2】:

    您打开了 3 个括号,但只关闭了 2 个。

    #define isPowerof2(n)  (!(n & (n-1)))
    

    但还有另一个错误。您应该在宏参数周​​围添加括号,否则您可能会遇到意外。

    #define isPowerof2(n)  (!((n) & ((n)-1)))
    

    编辑:错误示例

    调用

    isPowerOf2(34 >> 1)  which is not a power of 2
    

    会失败,因为在你没有括号的情况下,它将被扩展为

    (!(34 >> 1 & (34 >> 1-1)))
    (!(17 & (34 >> 0))       // shift is lower priority than subtraction
    (!(17 & 34))
    (!0)
    1
    

    这显然是错误的。

    固定宏的实际值为

    (!((34 >> 1) & ((34 >> 1)-1)))
    (!(17 & (17-1))       // shift is lower priority than subtraction
    (!(17 & 16))
    (!16)
    0
    

    【讨论】:

      猜你喜欢
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多