Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 以下宏用法有什么问题?_C_Syntax_Macros_Compiler Errors - Fatal编程技术网

C 以下宏用法有什么问题?

C 以下宏用法有什么问题?,c,syntax,macros,compiler-errors,C,Syntax,Macros,Compiler Errors,ispowerrof(2)inmain()causesexpected);错误…这有什么问题 #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); p

ispowerrof(2)
in
main()
causesexpected);错误…这有什么问题

#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(n)(!(n&(n-1))
int main(){
int n,p;
clrsc();
printf(“\n输入要检查的编号:”);
scanf(“%d”和“&n”);
isPowerof2(n);
printf(“%d”,p);
getch();
}

您又少了一个括号:

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

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

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

#define isPowerof2(n)  (!(n & (n-1)))
但是还有另一个bug。您应该在宏参数周围添加括号,否则您可能会感到意外

#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

顺便提一下,
ispowerrof2
中的表达式将指示零是2的幂,这是不正确的。