0%

C语言 赋值运算符

C语言的赋值运算符

​ 赋值运算符就是把表达式或者值赋给变量,比如极易混淆的=为赋值,等于是==

​ 其实赋值运算符可以和很多前面说的算术运算符、逻辑运算符和按位运算符合并使用。

​ 如下如下:

赋值运算符 含义
= 赋值,等于
+= 加后赋值
-= 减后赋值
*= 乘后赋值
/= 除后赋值
%= 取模后赋值
&= 按位与后赋值
|= 按位或后赋值
^= 按位异或后赋值
<<= 按位左移后赋值
>>= 按位右移后赋值

举个例子来show一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*advance/operator/operator2.c*/
#include <stdio.h>

int main()
{
int a;
printf("a is %d\n", a);
a = 5; //0b101
printf("a is %d\n", a);

printf("%d += 2 -> %d \n", a, a += 2);
a = 5; //0b101
printf("%d -= 2 -> %d \n", a, a -= 2);
a = 5; //0b101
printf("%d *= 2 -> %d \n", a, a *= 2);
a = 5; //0b101
printf("%d /= 2 -> %d \n", a, a /= 2);
a = 5; //0b101
printf("%d %%= 2 -> %d \n", a, a %= 2);
a = 5; //0b101
printf("%d &= 2 -> %d \n", a, a &= 2);
a = 5; //0b101
printf("%d |= 2 -> %d \n", a, a |= 2);
a = 5; //0b101
printf("%d ^= 2 -> %d \n", a, a ^= 2);
a = 5; //0b101
printf("%d <<= 2 -> %d \n", a, a <<= 2);
a = 5; //0b101
printf("%d >>= 2 -> %d \n", a, a >>= 2);

return 0;
}

相应地Makefile如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#advance/operator/Makefile

ALL : operator1 operator2

operator1: operator1.c
gcc -o operator1 operator1.c

operator2: operator2.c
gcc -o operator2 operator2.c

.PHONY : clean

clean:
rm -f operator1 operator2

输入make,然后./operator2输出为:

1
2
3
4
5
6
7
8
9
10
11
12
a is 107106770
a is 5
5 += 2 -> 7
5 -= 2 -> 3
5 *= 2 -> 10
5 /= 2 -> 2
5 %= 2 -> 1
5 &= 2 -> 0
5 |= 2 -> 7
5 ^= 2 -> 7
5 <<= 2 -> 20
5 >>= 2 -> 1

可以看到结果就是对每一位进行的操作

那么问题来了,你知道为什么a刚开始的值是107106770吗,为什么每次都给a赋值吗?

处无为之事,行不言之教;作而弗始,生而弗有,为而弗恃,功成不居!

欢迎关注我的其它发布渠道