[C Language Elementary] Take you to easily play with all common operators (2) - assignment operator, unary operator

insert image description here

Junxi_'s personal homepage

Be diligent and encourage the years to wait for no one

C/C++ game development


Hello, this is Jun Xi_, today I will bring you the second part of the content about operators, without further ado, let's start directly!

  • Before the official start, we still use a mind map to help briefly recall the basic content of operators

insert image description here

  • Let's continue what we said before:

1. Assignment operator

The assignment operator is a very useful operator that allows you to get a value that you were not happy with before. That is, you can reassign yourself

int weight = 120;//体重
weight = 89;//不满意就赋值
double salary = 10000.0;
salary = 20000.0;//使用赋值操作符赋值。
  • 赋值操作符也可以连续赋值
int a = 10;
int x = 0;
int y = 20;
a = x = y+1;//连续赋值
//但是同样的语义我们也可以下面这样
x = y+1;
a = x;
//这样的写法是不是更加清晰爽朗而且易于调试。
  • So we generally don't particularly recommend continuous assignment.

compound assignment operator

  • plus equals +=
  • minus equal to -=
  • multiply equals to *=
  • divide by equal/=
  • The remainder is equal to %=
  • shift right is equal to >>=
  • shift left is equal to <<=
  • bitwise and equals &=
  • bitwise or equal |=
  • bitwise XOR is equal to ^=
  • These operators can all be written as composite effects.

比如:
int x = 10;
x = x+10;
x += 10;//复合赋值与上一行意思相同
//其他运算符一样的道理。这样写更加简洁

2. Unary operator

1. Introduction to unary operators

Logical inverse operation!
Negative value -
positive value +
address &
operand type length (in bytes) sizeof
binary bitwise inversion of a number ~
pre--, post-pre-
++, post-++
indirect access operator (dereference operator) *
forced type conversion (type)

  • Let me give you a few simple examples first, and then let's pick a few more important ones in the middle and explain them.

#include <stdio.h>
int main()
{
    
    
	int a = -10;
	int* p = NULL;
	printf("%d\n", !2);
	printf("%d\n", !0);
	a = -a;
	p = &a;
	printf("%d\n", sizeof(a));
	printf("%d\n", sizeof(int));
	printf("%d\n", sizeof a);//这样写行不行?
	//printf("%d\n", sizeof int);//这样写行不行?
}
  • Let's look at the results:
    insert image description here

2. Logical inverse operator!

  • Pay attention to the results of our operation above
printf("%d\n", !2);
printf("%d\n", !0);
  • We can see that these two output results are "0" and "1" respectively
  • That is to say! True (not 0) when false (ie value 0), ! False if not false (0)

3. Find the type length sizeof of the operand

  • The basic usage of sizeof is like this
sizof(所求类型)
  • However, we can see from the results of the above example:
    printf("%d\n", sizeof(a));
	printf("%d\n", sizeof(int));
	printf("%d\n", sizeof a);//这样写行不行?
  • For a variable, the parentheses of sizof can be omitted, but if the required length is a type, the parentheses must be added!

sizeof and arrays

  • Generally speaking, our sizeof is widely used to find the length and number of elements of an array.
  • Here is a practical example to illustrate

Use the dichotomy method to find a specific number in an ordered array, and print out the array subscript of the number.

int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };//升序
	
	int k = 7;
	int i = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);//利用数组的总大小除以数组中一个元素的大小,得到数组中一共存放了几个元素
	//1
	int left = 0;
	int right = sz-1;//数组下标是数组元素个数-1
	int flag = 0;//flag的作用是标志是否找到了
	//2
	while (left<=right)//当左右都指向同一个数时还没找到,说明此数不存在
	{
    
    
		int mid = (left + right) / 2;
		if (arr[mid] == k)
		{
    
    
			printf("找到了,下标是:%d\n", mid);
			flag = 1;//令flag等于1
			break;
		}
		else if (arr[mid] < k)//mid就比k小,舍去比mid更小的数
		{
    
    
			left = mid + 1;
		}
		else//mid比k大,舍去比mid大的数
		{
    
    
			right = mid - 1;
		}
	}
	//1 2
	if (flag == 0)//判断是否找到k,如果找到,flag应等于1
		printf("没找到\n");

	return 0;
}
  • Note here:
int sz = sizeof(arr) / sizeof(arr[0]);//利用数组的总大小除以数组中一个元素的大小,得到数组中一共存放了几个元素
  • Here we use sizeof to successfully get the number of array elements, which is convenient for us to perform binary search in the next step .

Several errors often occur during the use of sizeof

  • Here we still take you through the code to expand the next content
#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;
}
/*问:
(1)、(2)两个地方分别输出多少?
(3)、(4)两个地方分别输出多少*/
  • Let's see the result:

insert image description here

  • what happened? The two of us obviously calculated the size of the same array, why are the results different?

  • Here is the knowledge of arrays and pointers. Let me explain why:

  • 1. When an array is passed as a parameter between functions, what is passed is actually the address of the first element, so what is being calculated is the size of the address of the first element!

  • 2. For an int integer data, it occupies four bytes, 10 is 40 bytes, and a char type data only occupies 1 byte, and 10 is 10 bytes, which is the reason for the above answer.

  • At this point, there may be a little cute to ask, why does the char type here occupy 4 bytes? Didn't you say that a char type only occupies 1 byte?

  • Um…
    insert image description here

  • Pay attention, if you think so here, it means that you still haven't understood my explanation above. It is recommended to read more pointer-related content!

  • Although the incoming form we write here is two arrays

void test1(int arr[])
void test2(char ch[])
  • But actually we said that what is passed in is the address of the first element, which is actually a pointer, so we can also write like this:
void test1(int *arr)
void test2(char *ch)

insert image description here

  • The result is still correct.
  • As for the size of the pointer, under the same operating system, the size of all pointer types is the same. We use a 32-bit operating system here, and the size of the pointer variable is uniformly 4 bytes, while 64-bit is uniformly 8 bytes.

insert image description here

  • Now, I think you should understand the reasons for the above results!

4. Front ++ and front - -

In fact, there is nothing to talk about in this area. The only thing we need to pay attention to is that when using it, first perform ++ or - - operation before proceeding to the next step.

  • for example:
//前置++和--
#include <stdio.h>
int main()
{
    
    
  int a = 10;
  int x = ++a;
  //先对a进行自增,然后对使用a,也就是表达式的值是a自增之后的值。x为11。
  int y = --a;
  //先对a进行自减,然后对使用a,也就是表达式的值是a自减之后的值。y为10;
  return 0;
  }

5. Post ++ and Post - -

Contrary to the pre-++ and pre--, the post-post ++ - - is to wait for the expression to be executed before performing the ++ or - - operation

  • Examples are as follows:
//后置++和--
#include <stdio.h>
int main()
{
    
    
  int a = 10;
  int x = a++;
  //先对a先使用,再增加,这样x的值是10;之后a变成11;
  int y = a--;
  //先对a先使用,再自减,这样y的值是11;之后a变成10;
  return 0;
  }

Give an example to prove the priority of the front and back

Let's use a specific example to prove what I said above.

#include <stdio.h>
int main()
{
    
    
	int a, b, c;
	a = 5;
	c = ++a;
	b = ++c, c++, ++a, a++;
	b += a++ + c;
	printf("a = %d b = %d c = %d\n:", a, b, c);
	return 0;
}
  • To judge the output of the above code
  • Here is not a secret, and the answer is directly announced:
    insert image description here
  • Is it the same result as you thought?
  • Let's break it down

int main()
{
    
    
	int a, b, c;
	a = 5;
	c = ++a;//前置++ c=6
	b = ++c, c++, ++a, a++;//逗号表达式整个表达式的结果是最后一个表达式的结果,这里先记住这个结论,具体解释我们后面再说
	//此时b=a++,由于后置这里就是a,但是前面执行了++a,此时a的值为7所有b就等于7
	//执行完b表达式后,开始执行后置的++,此时c等于8,a也等于8
	b += a++ + c;//这句话写清楚点就是b=b+a++ +c,此时b=7+8+8=23
	//最后再执行一次a后置++,a的值变为9
	printf("a = %d b = %d c = %d\n:", a, b, c);
	return 0;
}
  • I analyze it this way, does the output result match the result we printed on the screen? After reading this example, have you deepened your understanding of pre-post ++ (- -)?

6. ~ Inverts bits in two's complement

//~ 按补码二进制位取反

int main()
{
    
    
	int a = 0;
	printf("%d\n", ~a);//?
	//00000000000000000000000000000000 -a的补码
	//11111111111111111111111111111111 - ~取反后的补码
	//11111111111111111111111111111110
	//10000000000000000000000000000001 -1//打印时打印的是该数的原码
	return 0;
}

insert image description here


7. Take address operator & and dereference operator *

  • Most of these two appear in pointers. In fact, there is nothing to talk about, so I won’t expand on them. I will post related blogs about pointers later.

8. Mandatory type conversion ()

  • When we refer to a certain library function or other functions, the input data type may not match the data type defined by the function. At this time, we need to force the input data into the required data type. However, as the saying goes, hard twisting is not sweet. In some cases, bugs may occur when using forced type conversion.

  • for example:

int main()
{
    
    
	int a = (int)3.14;//强制
	printf("%d\n", a);
	
	return 0;
}

insert image description here

  • We cast a float to an int.
  • But we can also clearly see the defect of this code, it loses the data after our decimal point, that is to say, it is easy to cause data loss in the process of forced type conversion!
  • application in function
  • We have seen such a piece of code in the direct generation of random numbers in three-moon chess:
srand((unsigned int)time(NULL));//把时间函数置空传给srand同时由于srand要求参数必须为unsigned int型,把time(NULL)强制类型转换一下

Summarize

  • This is the end of today's content. Today we talked about assignment operators and the specific use of unary operators. If you are still confused, you may wish to do it yourself. The knowledge in this area is a bit abstract and requires repeated practice to get familiar with it.
  • The above is the second part of the operator, and the detailed explanations of other operator applications will be updated in batches in the near future, so stay tuned! !
  • Well, if you have any questions, please ask me in the comment area or private message, see you next time!

It is not easy for a new blogger to create. If you feel that the content of the article is helpful to you, you may wish to click on this new blogger before leaving. Your support is my motivation to update! ! !

**(Ke Li asks you to support the blogger three times in a row!!! Click the comment below to like and collect to help Ke Li)**

insert image description here

Guess you like

Origin blog.csdn.net/syf666250/article/details/131378155