C language operator

Posted by samvelyano on Thu, 23 Dec 2021 17:06:32 +0100

preface

This article takes you to understand the operators of C language. This article introduces the usage and priority of operators in C language in detail, as well as the possible misoperations in use.

1. Arithmetic operator

SymbolOperation introduction
+Add the operands
-Subtract the operand
*Multiply the operands
/Divide the operand
%Carry out residual operation on the operation object

In addition to the% operator, several other operations can be used for integer and floating-point operations
%The two operands of the operator must be integers and return the remainder after division
/Operator performs integer division if both operands are integers. However, as long as there is a floating-point number, floating-point division is performed

design sketch:

2. Displacement operator

OperatorOperator nameDisplacement rule
<<Shift left operatorDiscard on the left and fill 0 on the right
>>Shift right operator1. Discard the right and fill the left with 0 (logical shift) 2. Discard the right and fill the left with the original sign bit of the value (arithmetic shift)

Sketch Map:

Displacement results:

The integer is shifted by one bit to the left, and the number of displaced bits is enlarged by 2 times (the number of moved bits is the exponent based on 2, and the number of displaced bits is n, which is enlarged by 2^n times)
The unsigned integer is shifted to the right by one bit, and the number displaced is reduced by 2 times (the number of bits moved is the exponent based on 2, shifted by N bits, and reduced by 2^n times)

Note: the displacement operator is only applicable to integers, and the numbers moved are unsigned integers. Do not move negative digits, which is not defined in the standard.
legend:

The displacement operator can be used to find the number of bits 1 in the binary of a number. For details, see Calculates the number of bits of 1 in a binary integer

3. Bitwise operator

OperatorOperator nameuse
&Bitwise ANDAll 1 is 1
|Bitwise ORAll 0 is 0
^Bitwise XORThe same is 0 and the difference is 1

Sketch Map:

Note: the operands of bit operators must be integers.

By the way, I'll tell you a very powerful interview question: how to complete the numerical exchange between two variables without creating temporary variables.

//General practice:
#include<stdio.h>
int main()
{
	int a=10;
	int b=20;
	int tmp=0;
	printf("Before exchange: a=%d,b=%d\n",a,b);
	tmp=a;
	a=b;
	b=tmp;
	printf("After exchange: a=%d,b=%d\n",a,b);
	return 0;
}
//No temporary variables (scheme I)
#include<stdio.h>
int main()
{
	int a=10;
	int b=20;
	printf("Before exchange: a=%d,b=%d\n",a,b);
	a=a+b;//Store the sum of a and b in a
	b=a-b;//Subtract b from their sum to get a
	a=a-b;//The above change is b. the original value of a is stored in b. now we only need to subtract the current b from their sum to get the original b
	printf("After exchange: a=%d,b=%d\n",a,b);
	return 0;
}//The disadvantage of this method is that it may overflow data. Separate a and b may be OK, but it may overflow as soon as they are added
//Handle with XOR:
#include<stdio.h>
int main()
{
	int a=10;
	int b=20;
	printf("Before exchange: a=%d,b=%d\n",a,b);
	a=a^b;
	b=a^b;
	a=a^b;
	printf("After exchange: a=%d,b=%d\n",a,b);
	return 0;
}//The disadvantage of this method is that it is only suitable for shaping and is not readable

Here is a diagram to explain the XOR code above

The value obtained by their XOR. Just XOR with one of them again to get the value of the other.

4. Assignment operator

The assignment operator is the simplest and best of all operators. It allows you to assign the value you want to a variable.

#include<stdio.h>
int main()
{
	float wealth=2000.0;//Like the money in your own cell phone
	wealth=4000.0;
	//If we think it's less, we'll double it and put in a number we want
	int a=10;
	int b=20;
	int c=0;
	c=a=b+a;//It is allowed to write code in this way, but it is not recommended
	//Writing code in this way is not conducive to debugging and readability is not high. It is recommended to write it separately
	
	a=a+b;
	c=a;
	return 0;
}

Compound assignor

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

These symbols are symbolic effects written by other symbols, such as:

#include<stdio.h>
int main()
{
	int a=10;
	a=a+10;
	//Equivalent to
	a+=10;
	return 0;
}

5. Monocular operator

SymbolApplication effect
!Logical reverse operation
-negative
+positive
&Get address
sizeofThe type length of the operand in bytes
~Bitwise negation of a number
- -Front, rear --
++Front and rear++
*Indirect access operator (dereference operator)
typeCast type
#include<stdio.h>
int main()
{
	int a=0;
	int b=!a;
	//The logical inverse operator turns the original true value into false
	if(b)
	{
		printf("hehe\n");
	}
	else
		printf("haha\n");
		
	//Below are negative values
	int a=-10;
	
	//Next is the address dereference operator
	int a=10;
	int* p=&a;
	*p=20;
	printf("%p\n",p);//What we get here is the address of the space of a
	printf("%d\n",a);//You can also write a here as * p
	//When the dereference operator is combined with the variable storing the address, it will directly point to the space of that address

	//sizeof and cast are described below
	char arr[10]="abc";
    printf("%d\n",sizeof(arr));//10 bytes
    //It calculates the size of the entire space
    printf("%d\n",strlen(arr));//The length of the string. It focuses on whether there is \ 0 in the memory. It calculates the number of characters that appear before \ 0
    int x=0x11223344;
    printf("%d\n",(short)x);
    //Cast x to short
    
    int a=10;
    printf("%d\n",sizeof(a));// 4
    printf("%d\n",sizeof a);//4
    printf("%d\n",sizeof(int));// 4

    int a=5;
    short s=10;
    printf("%d\n,sizeof(s=a+2));//  2. The expression inside sizeof does not participate in the operation
    printf("%d\n",s);//  10
    
    //What follows is~
    int a=0;
    int b=~a;
    printf("%d\n",b);// -1
    //Original code
    //00000000000000000000000000000000 -0
    //Inverse code
    //00000000000000000000000000000000 -0
    //Complement
    //00000000000000000000000000000000 -0
    //Negate (the complement of 0 is negated)
    //11111111111111111111111111111111 - -1

	//The following describes the pre (post) + + and--
	int a =10;
	int x=++a;
	printf("%d\n",x);
	int y=--a;
	printf("%d\n",y);
	x=a++;
	printf("%d\n",x);
	y=a--;
	printf("%d\n",y);
	return 0;
}

6. Relational operators

Symbol
>
<
>=
<=
==
!=

The relational operator is relatively simple and will not be introduced here
However, be careful not to write = = as =;

7. Logical operators

SymbolSymbol name
&&Logic and
||Logical or

When using logical operators, pay attention to the distinction between logical operators and bitwise operators

The results of if (A & B) and if (A & & B) are different

#include <stdio.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);
//Because it is a postposition + +, it operates first, then a and then + 1, but the logical and is a false and all false. The initialization value of a is 0. In the computer, 0 is false, and non-0 represents true
//So the result is a=1,b=2,c=3,d=3

    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);
//Logic or all false is false, so when a is 0, it can continue to operate the following formula until it encounters an expression that is true and stops the operation
//The result is a=1,b=3,c=3,d=4

    return 0; 
}

8. Conditional operator

expression
exp1 ? exp2 : exp3
#include<stdio.h>
int main()
{
	int a = 10;
	int b = 20;
	int c = 0;
	c = a > b ? a : b;
	printf("%d\n",c);
	return 0;
}

9. Comma expression

exp1,exp2,exp3,exp4...expn

Comma expressions are multiple expressions separated by commas.
Comma expression, executed from left to right. The result of the entire expression is the result of the last expression.

#include<stdio.h>
int main()
{
	int a = 1;
	int b = 2;
	int c = (a>b, a=b+10, a, b=a+1);
	printf("%d\n",c);//c=13
	return 0;
}

10. Subscript references, function calls and structure members

Subscript reference operator []

#include<stdio.h>
int main()
{
	int arr[10]=0;//Create an array and initialize
	arr[9]=19;//Use subscript reference operators
	return 0;
}

At this time, the two operands of [] are arr and 9 respectively

Function call operator ()

#include<stdio.h>
void test1()
{
	test2();//A function can be nested to call another function, but it cannot be nested to create a function
	/*void test3()
	{
		printf("haha\n");//This writing method here is not allowed. It is not allowed to create another function in the function
	}*/
}
void test2()
{
	printf("hehe\n");
}
int main()
{
	test1();
	test2();
	return 0;
}

Accept one or more operands. The first operand receives the function name, and the remaining operands pass parameters to the function

Accessing members of a structure
. Structure member name
->Structure pointer - > member name

#include <stdio.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;//Structure member access
}
int main()
{
    struct Stu stu;
    struct Stu* pStu = &stu;//Structure member access
    
    stu.age = 20;//Structure member access
    set_age1(stu);
    
    pStu->age = 20;//Structure member access
    set_age2(pStu);
    return 0;
}
#include<string.h>
#include<stdio.h>
struct Book
{
	char name[20];
	int num;
	double price;
};
int main()
{
	struct Book book1 = { "C Language programming" ,12234334 ,34.2 };
	//book1.name="Java language design" / / this is a wrong format. In the Book class, name is an array of char variables. The array cannot be assigned directly in this way
//If you want to change, you need to use the strcpy function
	strcpy(book1.name ,"Java Language design");
	return 0;
}

11. Arithmetic conversion

If the operands of an operator are of different types, the operation cannot be performed unless one of the operands is converted to the type of the other operand. The following hierarchy is called ordinary arithmetic conversion.

long double
double
float
unsigned long int
long int
unsigned int
int

If the type of an operand is low in the above list, it must be converted to the type of another operand before performing the operation.
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 precision loss

12. Priority

The basic priorities need to remember:
The pointer is optimal, and monocular operation is better than binocular operation. Such as sign.
First arithmetic operation, then shift operation, and finally bit operation.
Logical operations are finally combined.

Because the priority text is too long, the blogger will not put it here for you. Here is the priority Du Niang website, you can go and have a look.
priority