The shorthand understanding of a++ and ++a in C language

     It's easy to get confused when understanding a++ and ++a (undefiend behavior), but when you use them, you can basically not make mistakes as long as you avoid complex and difficult expressions. If you need to fully understand the difference between the two, you need to read the assembly language of both.

 

Let’s talk about my shorthand understanding:

The first

a ++, the name of the increment, because plus Well, this is easy to understand in the back, then to the next step to think, why is it called the self-energizing it, because it is the first assignment, the increment operator. That is, the following b=a++, which is equivalent to the following:

int a = 1 ;

// b = a++ ; 与下面等价


b = a;  //先赋值
a = a +1;//后自增

a=1; b=++a; After execution, b is 1 and a is 2 . When you see a++ in the future, just call it post-increment, and then think about why it is called, so that you can basically understand it at a macro level.

 

Think in the same way++a

++ a, name before the increment, because plus Well, this is easy to understand in the front, next to that thinking, why is it called increment before it, because it is the first increment operator, carrying out the assignment operator, in. That is, the following b=++a, which is equivalent to the following:

int a = 1 ;

// b = ++a ; 与下面等价


a = a +1;//先自增
b = a;  //后赋值

a=1; b=++a; After execution, b is 2 and a is 2 . Note that the results after the two operations are different, the former auto-increment b is 1, and the latter auto-increment b is 2. When you see ++a in the future, just call it pre-increment. . . .

Type 2

The second one is a bit more winding, not as intuitive as the first one, so let’s go directly to the code.

int a = 5;
 
// int b 相当于:5 + 6 + 7 = 18      
     

 int b = a++ + a++ + a;
// 执行完a++[运算]后a进行自增,不是执行完此条完整语句后a才自增,而是在同一条语句中a++以后的a都是自增以后的值  
 // a经过两次自增,所以它的值是7
int a = 5;
 
// int b 相当于:6 + 7 + 7 = 20      
     

 int b = ++a + ++a + a;
 * a先进行自增,然后执行++a[元运算表达式]时.并且在同一条语句中,++a以后的a的值,都是自增以后的值
 // a经过两次自增,所以它的值也是7

 

Guess you like

Origin blog.csdn.net/qq_39463175/article/details/109069574