算术操作符
+加 -减 *乘 /除 %求模取余
- 除了%操作符以外,其余操作符皆可用于整数和浮点数
- /操作符,两操作数如果都是整数,执行整数除法,若至少有一个是浮点数,则进行浮点数除法
- %操作符的两个操作数必须为整数,返回值是整除后的余数
移位操作符
<<左移操作符
- 左边抛弃,右边补零
>>右移操作符
- 逻辑移位:左边补零,右边抛弃
- 算术移位:左边用该值的符号位补充,右边抛弃
注意:
- 移动的是二进制位
- 不能移动负数位
- 移动的值在没有被赋值的情况下,自身值不会改变
例题:求一个整数存储在内存中的二进制中1的个数
#include<stdio.h>
#include<windows.h>
int main()
{
int num = 10;
int count = 0;
while (num)
{
if (num%2==1)
{
count++;
}
num = num / 2;
}
printf("二进制中1的个数=%d\n", count);
system("pause");
return 0;
}
但是值是负数时不能计算
优化
#include<stdio.h>
#include<windows.h>
int main()
{
int num =-100;
int i = 0;
int count = 0;
for ( i = 0; i < 32; i++)
{
if (((num>>i)&1)==1)
{
count++;
}
}
printf("二进制中1的个数=%d\n", count);
system("pause");
return 0;
}
位操作符
& 按位与
| 按位或
^ 按位异或
注意:操作数必须为整数
例题:实现两个数的交换
#include<stdio.h>
#include<windows.h>
int main()
{
int a = 1;
int b = 2;
a = a^b;
b = a^b;
a = a^b;
printf("a=%d b=%d", a, b);
system("pause");
return 0;
}
赋值操作符
= 重新赋值
复合赋值符
+= -= *= /= %= >>= <<= &= |= =
单目操作符
单目操作符:即只有一个操作数
!逻辑反操作 -负值 +正值 &取地址
sizeof求操作数的类型长度 ~对一个数的二进制位按位取反
--前置,后置-- ++前置,后置++
*解引用操作符--->通过其里面存的地址,找到其指向的空间
(类型)强制类型转换
- sizeof求变量(类型)所占空间的大小
#include<stdio.h>
#include<windows.h>
void test1(int arr[])
{
printf("%d\n", sizeof(arr));//4
}
void test2(char ch[])
{
printf("%d\n", sizeof(ch));//4
}
int main()
{
int arr[10] = { 0 };
char ch[10] = { 0 };
printf("%d\n", sizeof(arr));//40
printf("%d\n", sizeof(ch));//10
test1(arr);
test2(ch);
system("pause");
return 0;
}
关系操作符
> >= < <= != ==
逻辑操作符
&&逻辑与 ||逻辑或
#include<stdio.h>
#include<windows.h>
int main()
{
int i = 0, a = 0, b = 2, c = 3, d = 4;
i = a++ && ++b && d++;
printf("a = %d\n b = %d\n c = %d\nd = %d\n", a, b, c, d);
system("pause");
return 0;
}
#include<stdio.h>
#include<windows.h>
int main()
{
int i = 0, a = 0, b = 2, c = 3, d = 4;
i = a++||++b||d++;
printf("a = %d\n b = %d\n c = %d\nd = %d\n", a, b, c, d);
system("pause");
return 0;
}
条件操作符
exp1 ? exp2 : exp3
例题:
if (a > 5)
b = 3;
else
b = -3;
写成条件表达式:(a>5)?b=3:b=-3;或者b=(a>5)?3:-3;
逗号表达式
exp1 , exp2 , exp3 ,...,expN
- 从左向右依次执行
- 整个表达式的结果是最后一个表达式的结果
int a = 1;
int b = 2;
int c = (a>b, a=b+10, a, b=a+1);//逗号表达式
c是多少?13
#include<stdio.h>
#include<windows.h>
int main()
{
int a = 1;
int b = 2;
int c = (a>b, a = b + 10, a, b = a + 1);//逗号表达式
printf("c = %d\n", c);
system("pause");
return 0;
}
下标引用操作符
[ ]
int arr[10];//创建数组
arr[9] = 10;//实用下标引用操作符
函数调用操作符
()
#include<stdio.h>
#include<windows.h>
#include <stdio.h>
void test1()
{
printf("hehe\n");
}
void test2(const char *str)
{
printf("%s\n", str);
}
int main()
{
test1(); //实用()作为函数调用操作符。
test2("hello bit.");//实用()作为函数调用操作符。
system("pause");
return 0;
}
访问一个结构的成员
- 结构体.成员名
- 结构体指针->成员名
#include<stdio.h>
#include<windows.h>
struct Stu
{
char name[10];
int age;
char sex[5];
double score;
};
void set_age1(struct Stu stu)
{
stu.age = 18;
}
void set_age2(struct Stu* pStu)
{
pStu->age = 18;
}
int main()
{
struct Stu stu;
struct Stu* pStu = &stu;
stu.age = 20;
set_age1(stu);
pStu->age = 20;
set_age2(pStu);
system("pause");
return 0;
}