当前位置:网站首页>Operator details

Operator details

2022-06-24 09:50:00 ふり

One 、 Operator classification

  1. arithmetic operator
  2. Shift operator
  3. Positional exercises An allograph
  4. Assignment operator
  5. Monocular operators
  6. Relational operator
  7. Logical operators
  8. Conditional operators
  9. Comma expression
  10. Subscript reference 、 Function calls and structure members

Two 、 Arithmetic operators

+    -   *   /   %
  1. except % Besides the operator , Several other operators can act on integers and floating point numbers .
  2. about / Operator if both operands are integers , Perform integer division . As long as there are floating-point numbers, it is floating-point division .
  3. % The two operands of an operator must be integers . What is returned is the remainder after integral division .

notes 1 :% Can only be used for integers

 Insert picture description here

notes 2 : about / The operator
1. If both operands are integers , Perform integer division .
2. As long as there are floating-point numbers, it is floating-point division

 Both operands are integers , Perform integer division

 As long as there are floating-point numbers, it is floating-point division

3、 ... and 、 Shift operator

 Shift left operator   : <<
 Shift right operator   :  >>  

notes : The operands of the shift operator It can only be integers . Moving bits

3.1 Binary system

There are three kinds of binary integers :

  1. Original code
  2. Inverse code
  3. Complement code

notes :

  1. Positive integer source code 、 Inverse code 、 The complement is the same
  2. Negative integer source code 、 Inverse code 、 The complement needs to be calculated
  3. Integers are in memory , What's stored is the complement
 Example :
 Integers  7
 Original code  :0000 0000 0000 0000 0000 0000 0000 0111
 Inverse code  :0000 0000 0000 0000 0000 0000 0000 0111
 Complement code  :0000 0000 0000 0000 0000 0000 0000 0111

 Negtive integer  -7
 Original code  :1000 0000 0000 0000 0000 0000 0000 0111
 Inverse code  :1111 1111 1111 1111 1111 1111 1111 1000       The sign bit of the original code remains unchanged , Other bits are reversed 
 Complement code  :1111 1111 1111 1111 1111 1111 1111 1001       Inverse code +1

3.2 Shift left operator ( Move binary )

Moving left is simple , Shift rules :

Abandon on the left , Zero on the right
notes : Can only be applied to integers

Positive examples

 Insert picture description here

Negative example

 Insert picture description here

3.3 Shift right operator

Shift rules :

  1. Logical shift :
    Use... On the left 0 fill , On the right side of the discarded
  2. Arithmetic shift :
    The left is filled with the sign bit of the original value , On the right side of the discarded

Positive examples

 Insert picture description here Negative example

 Insert picture description here

From this we can also draw a conclusion , Most compilers use arithmetic shifts to compute

notes : For shift operators , Don't move negative digits , This is not defined by the standard .

int num = 10;
num>>-1;//error

Four 、 Bit operators

Bit operators have :

  1. & // Bitwise AND ------- The same is the same , For the other 0
  2. | // Press bit or -------- One is one
  3. ^ // Bitwise XOR ------ Same as 0, Different for 1

notes : Operands must be integers , And according to the bits of binary , primary , back , Complement operation

4.1 Bitwise AND &

&
Bitwise AND ------- The same is the same , For the other 0

 Insert picture description here

4.2 Press bit or |

|
Press bit or -------- One is one

 Insert picture description here

4.3 Bitwise XOR ^

^
Bitwise XOR ------ Same as 0, Different for 1

 Insert picture description here

4.4 Exercise one

Cannot create temporary variable ( The third variable ), Realize the exchange of two numbers

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

 Insert picture description here

4.5 Exercise 2

Find an integer stored in binary in memory 1 The number of .

 Method 1  :
#include <stdio.h>
int main()
{
    
	int num = 10;
	int count = 0;// Count 
	while (num)
	{
    
		if (num % 2 == 1)
		{
    
			count++;
		}
		num = num / 2;
	}
	printf(" Binary 1 The number of  = %d\n", count);
	return 0;
}
** notes  :%2 and /2 Each bit of the binary number can be calculated in turn **
 Method 2  :
#include <stdio.h>
int main()
{
    
	int num = 10;
	int count = 0;// Count 
	int i = 0;
	for (i = 0;i < 32;i++)
	{
    
		if (num & (1 << i))
		{
    
			count++;
		}
	}
	printf(" Binary 1 The number of  = %d\n", count);
	return 0;
}
 notes  : hold 1 The binary of is shifted to the left in turn , Use bitwise and , A fellow 1 It's just 1 Easy to calculate 
 Method 3  :
#include <stdio.h>
int main()
{
    
	int num = 10;
	int count = 0;// Count 
	int i = 0;
	while (num)
	{
    
		count++;
		num = num & (num - 1);
	}
	printf(" Binary 1 The number of  = %d\n", count);
	return 0;
}
 Method 3 explain  : 
num = 0000 0000 0000 0000 0000 0000 0000 1010
num - 1 =0000 0000 0000 0000 0000 0000 0000 1001
num = num & (num - 1) 0000 0000 0000 0000 0000 0000 0000 1000
num - 1 = 0000 0000 0000 0000 0000 0000 0000 0111
num = num & (num - 1) 0000 0000 0000 0000 0000 0000 0000 0000

5、 ... and 、 Assignment operator

The assignment operator is a great operator , He can give you a value that you were not satisfied with before . That is, you can re assign yourself .

int weight = 120; 				// weight 
weight = 89;					// If you are not satisfied, you can assign a value 
double salary = 10000.0;
salary = 20000.0;				// Use the assignment operator to assign 

5.1 Compound assignor

+=                 
-=
*=
/=
%=
>>=
<<=
&=
|=
^=

x = x+10;
x += 10;// Compound assignment
// The same is true for other operators . It's more concise .

6、 ... and 、 Monocular operators

The unary operator has only one operand

!            Logical anti operation 
-            negative 
+            Comes at a time 
&            Address fetch 
sizeof       The type length of the operands ( In bytes )
~            To reverse the binary of a number 
--           In front of 、 After --
++           In front of 、 After ++
*            Indirect access operators ( Dereference operator ) 
 ( type )        Cast 

#include <stdio.h>
int main()
{
    
	int a = -10;
	int* p = NULL;
	printf("%d\n", !2);//c In language 0 For false , Not 0 It's true 
	printf("%d\n", !0);
	a = -a;
	p = &a;
	printf("%d\n", a);
	printf("%p\n", p);
	a = ~a;
	printf("%d\n", a);
	printf("%d\n", sizeof(a));
	printf("%d\n", sizeof(int));
	return 0;
}
0
1
10
009FF728
-11
4
4

6.1 sizeof And an array

#include <stdio.h>
void test1(int arr[])
{
    
	printf("%d\n", sizeof(arr));//(2)
}
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));//(1)
	printf("%d\n", sizeof(ch));//(3)
	test1(arr);
	test2(ch);
	return 0;
}
// ask :
//(1)、(2) How much is output from the two places ? 40 4
//(3)、(4) How much is output from the two places ? 10 4
  Whether it's characters , Or integer , The address is 4 Bytes or 8 Bytes 
  The first element address is passed 
 int  One is 4
 char     yes 1

6.2 ++ and - - Operator

// In front of ++ and --
#include <stdio.h>
int main()
{
    
	int a = 10;
	int x = ++a;
	// First pair a Since it increases , Then use a, That is, the value of the expression is a The value after self increase .x by 11.
	int y = --a;
	// First pair a Since the subtract , Then use a, That is, the value of the expression is a The value after subtraction .y by 10;
	return 0;
}
// After ++ and --
#include <stdio.h>
int main()
{
    
	int a = 10;
	int x = a++;
	// First pair a First use , add , such x The value of is 10; after a become 11;
	int y = a--;
	// First pair a First use , And then reduce , such y The value of is 11; after a become 10;
	return 0;
}

7、 ... and 、 Relational operator

>
>=
<
<=
!=    Used for testing “ It's not equal ”
==       Used for testing “ equal ”

These relational operators are relatively simple , There's nothing to say , But we should pay attention to some pitfalls when using operators .

Warning : In the process of programming == and = Accidentally make a mistake , The resulting error

7.2 Compare strings

#include <stdio.h>
int main()
{
    
	if ("abc" == "abcdef")
	{
    
		// This compares the addresses of the first letters of two strings 
		// The two strings should be compared  strcmp  function 
	}
	return 0;
}

strcmp and strcpy

 Insert picture description here

#include <stdio.h>
#include <string.h>
int main()
{
    
    char str1[15];
    char str2[15];
    int ret;
    strcpy(str1, "abcdef");        // Copy string 
    strcpy(str2, "abc");
    ret = strcmp(str1, str2);
    if (ret < 0)
    {
    
        printf("str1  Less than  str2");
    }
    else if (ret > 0)
    {
    
        printf("str1  Greater than  str2");
    }
    else
    {
    
        printf("str1  be equal to  str2");
    }
    return(0);
}

str1  Greater than  str2

8、 ... and 、 Logical operators

&&           Logic and ( Both the left and the right are true )   < also >
||           Logic or ( Left and right only need one side to be true )< perhaps >
#include <stdio.h>
int main()
{
    
	int a = 3;
	int b = 5;
	int c = a && b;					// Logic and 
	int d = a || b;					// Logic or 
	printf("%d\n", c);
	printf("%d\n", d);
	return 0;
}

8.1 An interview question

&&    The left is false , The right side doesn't count 
||    True on the left , The right side doesn't count 
#include <stdio.h>
int main()
{
    
    int i = 0, a = 0, b = 2, c = 3, d = 4;

    i = a++ && ++b && d++;
    //i = a++||++b||d++;
    printf("a = %d\nb = %d\nc = %d\nd = %d\n", a, b, c, d);
    return 0;
}
// What is the result of the program output ?
#include <stdio.h>
int main()
{
    
    int i = 0, a = 1, b = 2, c = 3, d = 4;
    
    i = a++ && ++b && d++;
    //i = a++||++b||d++;
    printf("a = %d\nb = %d\nc = %d\nd = %d\n", a, b, c, d);
    return 0;
}
// What is the result of the program output ?

 Insert picture description here

Nine 、 Conditional operators

The conditional operator is also a trinocular operator

 expression  1 ?  expression  2 :  expression  3  
   really          count          No   count 
   false         No   count         count 
if (a > 5)
        b = 3;
else
        b = -3;
 Convert to conditional expression , What is it like ?
(a > 5) ? (b = 3) : (b = -3);

Compare the number size with the ternary operator

#include <stdio.h>
int main()
{
    
    int a = 0;
    int b = 0;
    scanf("%d %d", &a, &b);
    int Max = ((a > b) ? a : b);
    printf("%d\n", Max);
    return 0;
}

Ten 、 Comma expression

expression 1 , expression 2 , expression 3 ,…

Comma expression , Is multiple expressions separated by commas .
Comma expression , From left to right . Of the entire expression result yes The result of the last expression .

int main()
{
    
    int a = 1;
    int b = 2;
    int c = (a > b, a = b + 10, a, b = a + 1);
    printf("%d\n", c);                       // 13
    return 0;
}
 if (a = b + 1, c = a / 2, d > 0)      // use  d  To judge 

11、 ... and 、 Subscript reference 、 Function calls and structure members

11.1 [ ] Subscript reference operator

Operands : An array name + An index value

int arr[10];                         // Create array 
arr[9] = 10;                         // Practical subscript reference operator .
//*(arr + 9)
//arr Is the address of the first element of the array 
//arr + 9 Is to skip nine dollars , Access the tenth element 
//*(arr + 9) Access the tenth element  
[] The two operands of are arr and 9.

11.2 ( ) Function call operator

#include <stdio.h>
int main()
{
    
    int a = 10;
    int b = 20;
    int c = Add(a, b);     // ( ) Is a function call operator , Operands :Add,a,b
    return 0;
}

11.3 Access members of a structure

.                     Structure . Member name 
->                    Structure pointer -> Member name 
#include <stdio.h>
struct Stu
{
    
	char name[20];
	int age;
	double score;
};
void set_stu(struct Stu* ps)
{
    
	/*strcpy((*ps).name ,"zhangsan"); (*ps).age = 20; (*ps).score = 100.0;*/
	strcpy(ps->name, "zhangsan");
	ps->age = 20;
	ps->score = 100.0;
}
void print_stu(struct Stu* ps)
{
    
	printf("%s %d %lf\n",ps->name, ps->age, ps->score);
}
int main()
{
    
	struct Stu s = {
     0 };
	set_stu(&s);
	print_stu(&s);
	return 0;
}

Twelve 、 Expression evaluation

The order in which expressions are evaluated is partly determined by the precedence and associativity of the operators .
Again , The operands of some expressions may need to be converted to other types during evaluation

12.1 Implicit type conversion

C Integer arithmetic operations are always performed at least with the precision of the default integer type .
To get this accuracy , Characters and short operands in expressions are converted to normal integers before use .
This transformation is called Improve the overall shape .

The significance of integer Promotion :

  1. The integer operation of expression should be in CPU In the corresponding computing device of ,CPU Inner integer arithmetic unit (ALU) The byte length of the operands of
  2. It is commonly int Byte length of , It's also CPU The length of the general register of .
    therefore , Even two char The addition of types , stay CPU When executing, it should be converted to CPU The standard length of the inner operands .
  3. Universal CPU(general-purpose CPU) It is difficult to realize two directly 8 Direct addition of bits and bytes ( Although machine instructions
    There may be such byte addition instructions in ). therefore , Various lengths in expressions may be less than int The integer value of the length , You have to turn first
    Replace with int or unsigned int, Then it can be sent in CPU To perform the operation .

Let's guess the result

#include <stdio.h>
int main()
{
    
	char a = 5;
	char b = 126;
	char c = a + b;
	printf("%d\n", c);
	return 0;
}

 Insert picture description here
notes :a and b The value of is promoted to a normal integer , Then perform the addition operation . After the addition operation is completed , The result will be truncated , Then store it in c in .

How to carry out plastic improvement

  1. Integer promotion is promoted according to the sign bit of the data type of the variable
// The shaping and lifting of negative numbers 
char c1 = -1;
 Variable c1 Binary bit of ( Complement code ) There are only 8 A bit :
1111111
 because  char  For signed  char
 So when shaping and improving , High supplementary sign bit , That is to say 1
 The result of ascension is :
11111111111111111111111111111111

// Positive integer lifting 
char c2 = 1;
 Variable c2 Binary bit of ( Complement code ) There are only 8 A bit :
00000001
 because  char  For signed  char
 So when shaping and improving , High supplementary sign bit , That is to say 0
 The result of ascension is :
00000000000000000000000000000001

// No sign plastic lift , High compensation 0
// example 1
#include <stdio.h>
int main()
{
    
	char a = 0xb6;
	short b = 0xb600;
	int c = 0xb6000000;
	if (a == 0xb6)
		printf("a");
	if (b == 0xb600)
		printf("b");
	if (c == 0xb6000000)
		printf("c");
	return 0;
}
// example 1 Medium a,b It's going to be a plastic lift , however c There is no need for plastic lifting 
//a,b After shaping and lifting , It becomes a negative number , So the expression  a==0xb6 , b==0xb600  The result is false , however c No plastic lifting occurs , Schedule 
// Da da  c==0xb6000000  The result is true .

The output of the program is : c

// example 2
#include <stdio.h>
int main()
{
    
	char c = 1;
	printf("%u\n", sizeof(c));
	printf("%u\n", sizeof(+c));
	printf("%u\n", sizeof(-c));
	return 0;
}
// example 2 Medium ,c Just participate in the expression operation , There will be plastic improvement , expression  +c , There will be ascension , therefore  sizeof(+c)  yes 4 A word 
// section .
// expression  -c  Plastic lifting can also occur , therefore  sizeof(-c)  yes 4 Bytes , however  sizeof(c) , Namely 1 Bytes .

12.2 Arithmetic conversion

If the operands of an operator belong to different types , Then unless one of the operands is converted to the type of the other operand , Otherwise, the operation cannot be carried out .

// From high priority to low priority 
long double
double
float
unsigned long int
long int
unsigned int
int

If the type of an operand is lower in the list above , Then first convert to the type of another operand and execute the operation
count .
Warning :
But the arithmetic conversion should be reasonable , Otherwise there will be some potential problems .

float f = 3.14;
int num = f;         // Implicit conversion , There will be loss of accuracy 

12.3 The properties of the operator

There are three factors that affect the evaluation of complex expressions .

  1. The priority of the operator
  2. The associativity of operators
  3. Whether to control the order of evaluation .

Which of the two adjacent operands should be executed first ? Depending on their priorities . If both have the same priority , Depending on their combination .

原网站

版权声明
本文为[ふり]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240904042617.html