An article on C language operators (detailed explanation with examples)

Table of contents

1. What is an operator?

Basic Features

Semantics

priority

Combination

2. Classification of operators

3. Detailed explanation of various types of operators

1. Arithmetic operators (+ - * / %)

(1) Priority:

(2) Calculation rules and precautions for the division operator (/)

(3) Calculation rules for the remainder operator (%)

(4) Arithmetic operator sample code

2. Shift operator (>> <<)

(1) Priority:

(2) Calculation rules and precautions

(3) Shift operator sample code

3. Bitwise operators (& ^ |)

 (1) priority

(2) Calculation rules and precautions

(3) Sample interview questions

(4) Bit operator sample code

4. Assignment operator ( = += -= *= /= %= ………)

(1) Priority (the priority of assignment operators is very low)

 (2) Operation rules

(3) Assignment operator sample code

5. Unary operator

(1) Introduction to unary operators

(2) What are the unary operators?

(3) sizeof and array

(4) Sizeof and array sample code:

6. Relational operators (< > <= >=)

(1) priority

 (2) Introduction of relational operators

(3) Operation result value

(4) Precautions

(5) sample code

7. Logical operators (&& ||)

(1) What is a logical operator?

(2) Priority

(3) Calculation rules

(4) The characteristics of the computer in calculation:

(4) Examples

8. Conditional operator ( : ? )

(1) priority

(2) Operation rules:

(3) Code example

9. Comma expression ( , )  

(1) priority

(2) Introduction and operation rules of comma expressions

example:

10. Subscript references, function calls and structure members ( [ ] () . -> )

(1) priority

(2) Subscript reference operator ( [ ])

(3) Function call operator ( ( ) )

(4) Structure member access operator ( -> . )

4. Operator priority table (including memory rules)

1. List of operator precedence and associativity

2. The rules in the table:


1. What is an operator?

Each instruction of the instruction system has an operator, which indicates what kind of operation the instruction should perform. Different instructions are represented by different encodings of the operator field, and each encoding represents an instruction.

Basic Features

Semantics

Each operator has its own semantics, depending on the type it operates on. 

priority

Every operator has a precedence. 

Combination

Every operator has associativity.  The associativity of an operator defines the order in which the operator performs operations on its operands, for example: right associativity means that the operator performs operations on its operands from right to left.

2. Classification of operators

Operator classification
arithmetic operator  +      -      *      /     %
shift operator <<     >>     
bitwise operator &      |        ^     
assignment operator =      +=      -=     *=     /=      ……
unary operator !   sizeof    +      -      ~     &     *   ……
relational operator >        <        >=      <=      !=
logical operator &&      ||
conditional operator ?      :
comma expression ,
Subscript references, function calls and structure members [ ]       ()      .      ->

3. Detailed explanation of various types of operators

1. Arithmetic operators (+ - * / %)

(1) Priority:

 

(2) Calculation rules and precautions for the division operator (/)

The focus here is on the calculation of division

2.1 Division calculation classification

(1) Integer division (both ends of the division sign are integers)

(2) Floating-point division (floating-point division is performed if one of the two ends is a decimal)

2.2 Calculation rules and precautions

Note: In division, the dividend cannot be equal to 0

The result of integer division only retains the integer part, and directly rounds off after the decimal point, such as 15 / 5 =3 3 / 2 =1

Note: This is not rounding, it is directly rounding off the decimal part!

Both the integer and decimal parts of the result of floating-point division are reserved, and the precision of the result is generally 6 digits after the decimal point

For example 3 / 2.0 =1.500000   

           3.0 / 2 = 1.500000

           3.0 / 2.0 = 1.500000

Note: At least one of the two ends must be a decimal

(3) Calculation rules for the remainder operator (%)

Note: Both ends of the remainder operator must be integers

3.1 Calculation rules: 

For example, 5 % 2 = 1 (5 divided by 2 equals 2 with a remainder of 1)

            99 % 10 = 9

(4) Arithmetic operator sample code

int main()
{
	printf("%d\n",3+5);
	printf("%d\n",4-2);
	printf("%d\n",5*7);
	printf("%d\n",15/5);
	printf("%d\n",3/2);
	printf("%d\n",99%10);

	return 0;
}

output:

 


2. Shift operator (>> <<)

(1) Priority:

 

(2) Calculation rules and precautions

Note: The operands of shift operators can only be integers

2.1 Calculation rules

First , the shift operator shifts the two's complement binary information of the operand

(1) Right shift operator   

Right shift operator operation and examples:

 Note: the shift operator operand itself does not change; e.g. b = a>>1 above

Where b=7; and a itself is still 15

2.2 Left shift operator

Calculation rules: discard on the left, add 0 to the right

 

(3) Shift operator sample code

int main()
{
	int a = 15;
	int b = -15;
	int c = 6;
	int m = -6;
	int d = a >> 1;
	int e = b >> 1;
	int f = c << 1;
	int g = m << 1;
	printf("%d %d %d %d \n",d,e,f,g);

	return 0;
}

 output:


3. Bitwise operators (& ^ |)

Note: Like the shift operator, it also operates on the two's complement

 (1) priority

(2) Calculation rules and precautions

Note: their operands must be integers

(1) Bitwise AND &

Calculation Rules

The binary numbers corresponding to the two numbers are 0 if they have 0, and 1 if they are all 1;

(2) Bitwise XOR (^)

Calculation Rules

The binary bits corresponding to the two numbers are the same as 0, and the difference is 1;

Common conclusion: a^0=a;

                  a^a=0;

                  a^b^a=b; (support commutative law)

                  a^a^b=b;

(3) Sample interview questions

Title description: Do not create temporary variables to exchange the values ​​of a and b

Reference Code:

#include <stdio.h>
int main()
{
	int a = 10;
    int b = 20;
    printf("交换前:a = %d b = %d\n", a,b);
    a = a^b;
    b = a^b;
    a = a^b;
    printf("交换后:a = %d b = %d\n", a,b);
	return 0;
}

(3) Bitwise or ( | )

Calculation Rules

The binary numbers corresponding to the two numbers have 1, then it is 1, and all 0s are 0;

(4) Bit operator sample code

int main()
{
	int a = 3;
	int b = -5;
	printf("a=%d b=%d\n",a,b);
	printf("a&b=%d\n",a&b);
	printf("a|b=%d\n",a|b);
	printf("a^b=%d\n",a^b);
	printf("a^a=%d\n",a^a);
	printf("a^0=%d\n",a^0);
	printf("a^b^a=%d\n",a^b^a);
	printf("a^a^b=%d\n",a^a^b);

	return 0;
}

output

 



4. Assignment operator ( = += -= *= /= %= ………)

(1) Priority (the priority of assignment operators is very low)

 (2) Operation rules

Their operation rules are basically the same;

assignment operator
symbol Algorithm
a=3 3 assigned to a
a+=3 a=a+3
a-=3 a=a-3
a*3 a=a*3
a/=3 a=a/3
a%=3 a=a%3
a<<=3 a=a<<3
a>>=3 a=a>>3
a&=3 a=a&3
a|=3 a=a|3
a^=3 a=a^3

           

(3) Assignment operator sample code

int main()
{
	int a = 9;
	printf("a=%d\n",a);
	printf("a+=3的值为%d\n",a+=3);
	printf("a-=3的值为%d\n",a-=3);
	printf("a*=3的值为%d\n",a*=3);
	printf("a/=3的值为%d\n",a/=3);
	printf("a%=2的值为%d\n",a%=2);
	printf("a|=5的值为%d\n",a|=5);
	printf("a&=3的值为%d\n",a&3);
	printf("a^=2的值为%d\n",a^2);
	printf("a<<=1的值为%d\n",a<<=1);
	printf("a>>=1的值为%d\n",a>>=1);

	return 0;
}

output:

 


5. Unary operator

(1) Introduction to unary operators

Unary operator: only one operand

(2) What are the unary operators?

unary operator
logical inversion
- negative value
+ positive value
& take address
sizeof the type length of the operand in bytes
~ Bitwise inverse of a number
-- front, back--
++ pre, post ++
* indirect access operator (dereference)
(type) cast

Note: s izeof is not a function, but an operator

        The calculation is the size of the type created (in bytes)

(3) sizeof and array

(4) Sizeof and array sample code:

int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	char ch[6] = { 'a','b','c','d','e','f' };
	int a = sizeof(arr);                            //40
	int b = sizeof(ch);                             //6
	printf("int类型的大小%d\n",sizeof(int));         //4
	printf("char类型的大小%d\n",sizeof(char));       //1
	printf("数组arr的大小%d\n",a);                   //40
	printf("数组ch的大小%d\n",b);                    //6

	return 0;
}

output:

 


6. Relational operators (< > <= >=)

(1) priority

 (2) Introduction of relational operators

(3) Operation result value

The value of a relational operator can only be 0 or 1.

When the relational operator evaluates to true, the result value is 1.

When the relational operator evaluates to false, the result value is 0.

(4) Precautions

(1) The priority levels of the first four relational operators are the same, and the latter two are also the same. The first four are higher than the latter two.

(2) Relational operators have lower precedence than arithmetic operators.

(3) Relational operators have higher precedence than assignment operators. 

(5) sample code

int main()
{
	printf("%d\n",(-3>2));
	printf("%d\n",(3>=3));
	printf("%d\n",(2)&&(-1));
	printf("%d\n",(2<=9));
	printf("%d\n",(4<=4));

	return 0;
}

output:

 


7. Logical operators (&& ||)

(1) What is a logical operator?

Logical operators are operators used to test compound conditions in conjunction with bool values.

(2) Priority

(3) Calculation rules

Logical AND &&: () && () is true only if both are true, and one of them is false;

Logical OR | : ()|() If two are false, then it is false, and one of them is true, then it is true;

Note : (non-0 is true, 0 is false)

(4) The characteristics of the computer in calculation:

1. The computer calculation result is 1 for true, and 0 for false calculation;

For example: int a = (3>4) the result of a is 0; a=0;

           int  a = (3>2)        a的结果为1;a=1;

2..当&&操作符左边的为假,右边的都不用计算了;

(因为&&操作符有一个为假即为假)

例如 (3<2)&&(4>3)    左边条件为假   ,右边就不用算了,整个式子的结果就是假;

3..当||操作符左边为真,右边也不用计算了;

(因为||操作符其中一个为真即为真)

 例如   (3>2)||(4<9)     左边条件为真,右边就不用计算了,整个式子的结果就为真;

(4)例题

1.题目描述:printf(“%d”,(a=2)&&(b=-2));的输出结果()

答案:1

2.题目描述:int x=3,y=4,z=1;则表!(x+y)+z-1&&y+z/2的值为()

答案:0

解析:因为式子中运算符的优先级为  ()>  !  >  /  > +

所以左边的式子x+y=7(非0,为真),但是运算符!,结果变为假,所以结果为0;

0+z-1=0;左边为0,又因为是&&操作符,所以整个式子结果为假,即为0;

代码测试

int main()
{
	int a = 0;
	int b = 0;
	int x = 3;
	int y = 4;
	int z = 1;
	printf("%d\n",(a=2)&&(b=-2));
	printf("%d\n",!(x+y)+z-1&&y+z/2);

	return 0;
}

输出:

 


8.条件操作符(  :    ?  )

(1)优先级

(2)运算规则:

表达式为:表达式1:表达式2:表达式3

先计算表达式1的值,若表达式1为真,则执行表达式2;若表达式1为假,则执行表达式3;

例如;

max = (x > y) ? x : y           (就是把x,y中较大的赋给max)

min =  (x < y) ? x : y              (就是把x,y中较小的赋给min)

(3)代码示例

int main()
{
	int x = 4;
	int y = 3;
	int a = 2;
	int b = 6;
	int max = ((x > y) ? x : y);
	int min = ((a < b) ? a : b);
	printf("x=%d y=%d a=%d b=%d\n",x,y,a,b);
	printf("max=%d\n",max);
	printf("min=%d\n",min);

	return 0;
}

输出:

 


9.逗号表达式(   ,  )  

(1)优先级

逗号表达式的优先级最低

(2)逗号表达式的介绍及运算规则

逗号表达式,是c语言中的逗号运算符,优先级别最低,它将两个及其以上的式子联接起来,从左往右逐个计算表达式,整个表达式的值为最后一个表达式的值

如:(3+5,6+8)称为逗号表达式,其求解过程先表达式1,后表达式2,整个表达式值是表达式2的值,如:(3+5,6+8)的值是14;a=(a=3*5,a*4)的值是60,其中(a=3*5,a*4)的值是60, a的值在逗号表达式里一直是15,最后被逗号表达式赋值为60,a的值最终为60。

例题:

例题:(a = 3,b = 5,b+ = a,c = b* 5),求逗号表达式的值?

答案:40

解析:前两个表达式只是赋值,从第三个开始计算,b+=a,即b=b+a,即b=5+3,b=8,求最后一个表达式,c=b*5=8*5=40.因为逗号表达式的值是最后一个表达式的值,所以整个逗号表达式的值为40,其他各变量最后的值依次为:a=3,b=8,c=40


10.下标引用,函数调用和结构体成员  ( [ ]    ()   .   -> )

(1)优先级

(2)下标引用操作符( [ ])

操作数:一个数组名+一个引索值

如:

arr[10]={0};//创建数组

arr[9]=10;//使用下标引用操作符

[ ]的两个操作数是arr和9

(3)函数调用操作符(  ( ) )

1.操作数

函数名   +   函数参数

如   strlen("abc")      操作数为     strlen    "abc"

注意:函数的参数可能有多个,所以对于函数调用操作符()来说,操作数至少有1个(函数可以没有参数,如:test())

 2.示例代码

#include <string.h>

void test()
{
	printf("hello bit!");
}
int main()
{
	char ch[] = "abc";
	int len = strlen(ch);
	printf("%d\n",len);
	test();

	return 0;
}

(4)结构体成员访问操作符(  ->     .  )

.       结构体变量.成员名

->    结构体指针->成员名

示例代码

struct book
{
	char  name[20];
	char  author[20];
	float price;
};

void Print(struct book * p)
{
	printf("%s %s %.1f\n",p->author,p->name,p->price);
}

int main()
{
	struct  book a = { "小明","c语言",33.9f };
	Print(&a);
	printf("%s %s %.1f",a.author,a.name,a.price);

	return 0;
}

输出:

 

 


四.操作符优先级表(含记忆规律)

1.运算符优先级和结合性一览表

 

2.表中规律:

  1. 结合方向只有三个是从右往左,其余都是从左往右。
  2. 所有双目运算符中只有赋值运算符的结合方向是从右往左。
  3. 另外两个从右往左结合的运算符也很好记,因为它们很特殊:一个是单目运算符,一个是三目运算符。
  4. C语言中有且只有一个三目运算符。
  5. 逗号运算符的优先级最低,要记住。
  6. 此外要记住,对于优先级:算术运算符 > 关系运算符 > 逻辑运算符 > 赋值运算符。逻辑运算符中“逻辑非 !”除外。

谢谢观看!!!

                                                                                                                                    




Guess you like

Origin blog.csdn.net/2301_77509762/article/details/131280378