C语言易弄错优先级
1.".“的优先级高于”*","->"操作符用于消除这类问题
*p.f
误认:p所指对象的字段f。(*p).f
实际结果:对p取f偏移,作为指针,然后作为解除引用操作。*(p.f)*
2.[]优先级高于*
int *ap[]
误认:ap是个指向int数组的指针。 int (*ap)[]
实际结果:ap是个元素为int的指针数组。 int *(ap[])
3.函数()高于*
int *fp()
误认:fp是个函数指针,所指函数返回int。int (*fp)()
实际结果:fp是一个函数,返回值为int *。 int *(fp())
4.==和!=高于位运算
(val & mask != 0 )
误认:(val & mask) != 0
实际结果: val & (mask != 0)
5.==和!=高于赋值运算
c = getchar() != EOF
误认:(c = getchar()) != EOF
实际结果:c = (getchar() != EOF)
6.算术运算高于位运算
msb << 4 + lsb
误认:(msb << 4) + lsb
实际结果:msb << (4 + lsb)
7.","运算符在所有运算符中最低
[klaus@localhost keyword_study]$ cat priority.c
#include <stdio.h>
int main(void)
{
int i;
i=1,2;
printf("%d\n",i);
return 0;
}
[klaus@localhost keyword_study]$ gcc priority.c
[klaus@localhost keyword_study]$ ./a.out
1
[klaus@localhost keyword_study]$
注:本篇文章学习来自《c语言深度剖析》,侵权必删。