(++) and (--) operators in C#

Table of contents

background:

prefix of ++

Effect display:​

++ added after

Effect display:​

Summarize:


background:

   The auto-increment and auto-decrement operators exist in high-level languages ​​such as C/C++/C#/Java. Their function is to operate before the end of the operation (pre-increment and decrement operators) or after (post-increment and decrement operators). ) adds (or subtracts) 1 to the value of the variable.
    In C#, ++ and -- are the increment and decrement operators, used to add or subtract 1 to a variable. The execution operator can only be applied to modifiable variables (that is, the variable is a numeric type, a nullable numeric type, or a reference type). The code effects of ++ and -- are similar. The difference is that one is added and the other is subtracted, so I will use ++ as an example.

prefix of ++

 int num = 10;//定义一个num的整型变量,并将其初始化为10
 int number = ++num + 10;//先自身加1,然后再参与运算
 Console.WriteLine("num的值是{0}", num);//输出
 Console.WriteLine("number的值是{0}");//输出
 Console.ReadKey();//等待用户按键

Show results:

++ added after

int num = 10;//定义一个num的整型变量,并将其初始化为1
int number = 10 + num++;//先取num的原值参与运算,然后再自身+1
Console.WriteLine("num的值是{0}", num);//输出
Console.WriteLine("number的值是{0}",number);//输出;
Console.ReadKey();//等待用户按键

Show results :

Summarize:

In summary, it can be concluded from the above that the effects of front + and back + are similar. The only difference is that they participate in the operation. Front + participates in the operation first and adds 1 to itself, while rear + adds 1 to itself first and participates in the operation. The same goes for before-and-after.
Just remember two sentences: before + comes before, increment first and then calculate; after + comes last, calculate first and then increment. Pre- is in front, decrement is performed first, and post- is in the end, and decrement is performed first.
These operators are very common in C#, and they can be used in control structures such as loops and conditional statements, as well as to make simple modifications to variables. When writing code, use the increment and decrement operators to make your code more concise and readable.

Guess you like

Origin blog.csdn.net/weixin_59272777/article/details/133177024