Task1:二進制位操作符
#include <stdio.h>
#define PRINT(int) printf(#int " = %d\n",int)
int main(void)
{
int x,y,z;
/*
優先級:位運算符中:& > |
位運算符& > 邏輯運算符&&
*/
x = 03; y = 02; z = 01;
PRINT(x | y & z); //0011 | 0000 = 3
PRINT(x | y & ~ z); //0011 | 0010 = 3
PRINT(x ^ y & ~ z); //0011 ^ 0010 = 1
PRINT(x & y && z); //2 && 1 = 1
x = 1; y = -1;
PRINT(! x | x); //((!x) | x)=false | x = 1
// http://www.bianceng.cn
PRINT(~ x | x); //1111 = -1
PRINT(x ^ x); //0001 ^ 0001 = 0
x <<= 3;PRINT(x); //左移n位效果上看成乘以n個2 = 8
y <<= 3;PRINT(y); //………………………………&hellip ;= -8
y >>= 3;PRINT(y); //右移n位效果上看成除以n個2 = -1
return 0;
}
輸出結果:
x | y & z = 3
x | y & ~ z = 3
x ^ y & ~ z = 1
x & y && z = 1
! x | x = 1
~ x | x = -1
x ^ x = 0
x = 8
y = -8
y = -1
Task2:關系操作符和條件操作符
#include <stdio.h>
#define PRINT(int) printf(#int " = %d\n",int)
int main(void)
{
int x = 1, y = 1, z = 1;
x += y += z; //右結合,x = 3, y = 2, z = 1
PRINT( x < y ? y : x); //x = 3
PRINT( x < y ? x ++ : y ++); //輸出2,y = 3
PRINT(x);PRINT(y);//3,3
PRINT( z += x < y ? x ++ : y ++); //輸出4,z = z+3 = 4,y = 4
PRINT(y);PRINT(z);//4,4
x = 3; y = z = 4;
PRINT((z >= y >= x) ? 1 : 0); //(1>=3)?1:0 = 0
PRINT( z >= y && y >= x); //(z>=y)&&(y>=x)=true&&true=1
return 0;
}
輸出結果:
x < y ? y : x = 3
x < y ? x ++ : y ++ = 2
x = 3
y = 3
z += x < y ? x ++ : y ++ = 4
y = 4
z = 4
(z >= y >= x) ? 1 : 0 = 0
z >= y && y >= x = 1
Task3:操作符的優先級和求值順序
#include <stdio.h>
#define PRINT3(x,y,z) printf(#x "=%d\t" #y "=%d\t" #z "=%d\n",x,y,z);
int main(void)
{
int x,y,z;
x = y = z = 1;
++x || ++y && ++z; PRINT3(x,y,z); //2,1,1
x = y = z = 1;
++x && ++y || ++z; PRINT3(x,y,z); //2,2,1
x = y = z = 1;
++x && ++y && ++z; PRINT3(x,y,z); //2,2,2
x = y = z = -1;
++x && ++y || ++z; PRINT3(x,y,z); //0,-1,0
x = y = z = -1;
++x || ++y && ++z; PRINT3(x,y,z); //0,0,-1
x = y = z = -1;
++x && ++y && ++z; PRINT3(x,y,z); //0,-1,-1
return 0;
}
輸出結果:
x=2 y=1 z=1
x=2 y=2 z=1
x=2 y=2 z=2
x=0 y=-1 z=0
x=0 y=0 z=-1
x=0 y=-1 z=-1
查看本欄目