# 自增(++)和自减(--)

一个整数自身加一可以这样写：

```c
a+=1;
```

它等价于`a=a+1;`。

但是在C语言中还有一种更简单的写法，就是`a++;`或者`++a;`。这种写法叫做自加或自增；意思很明确，就是自身加一。

相应的，也有`a--`和`--a`，叫做自减，表示自身减一。

`++`和`--`分别称为自增和自减运算符。

自增和自减的示例：

```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a = 10, b = 20;
    printf("a=%d, b=%d\n", a, b);
    ++a;
    --b;
    printf("a=%d, b=%d\n", a, b);
    a++;
    b--;
    printf("a=%d, b=%d\n", a, b);

    system("pause");
    return 0;
}
```

运行结果：

```
a=10, b=20
a=11, b=19
a=12, b=18
```

自增自减完成后，会用新值替换旧值，并将新值保存在当前变量中。自增自减只能针对变量，不能针对数字，例如`10++`是错误的。

值得注意的是，++ 在变量前面和后面是有区别的：

* ++ 在前面叫做**前自增**（例如 ++a）。前自增先进行自增操作，再进行其他操作。
* ++ 在后面叫做**后自增**（例如 a++）。后自增先进行其他操作，再进行自增操作。

自减（--）也一样，有前自减和后自减之分。

请看下面的例子：

```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a=10, a1=++a;
    int b=20, b1=b++;
    int c=30, c1=--c;
    int d=40, d1=d--;

    printf("a=%d, a1=%d\n", a, a1);
    printf("b=%d, b1=%d\n", b, b1);
    printf("c=%d, c1=%d\n", c, c1);
    printf("d=%d, d1=%d\n", d, d1);

    system("pause");
    return 0;
}
```

输出结果：

```
a=11, a1=11
b=21, b1=20
c=29, c1=29
d=39, d1=40
```

a、b、c、d 的输出结果相信大家没有疑问，下面重点分析a1、b1、c1、d1：

1\) 对于a1=++a，先执行++a，结果为11，再将11赋值给a1，所以a1的最终值为11。而a经过自增，最终的值也为11。

2\) 对于b1=b++，b的值并不会立马加1，而是先把b原来的值交给b1，然后再加1。b原来的值为20，所以b1的值也就为20。而b经过自增，最终值为21。

3\) 对于c1=--c，先执行--c，结果为29，再将29赋值给c1，所以c1的最终值为29。而c经过自减，最终的值也为29。

4\) 对于d1=d--，d的值并不会立马减1，而是先把d原来的值交给d1，然后再减1。d原来的值为40，所以d1的值也就为40。而d经过自减，最终值为39。

可以看出：`a1=++a;`会先进行自增操作，再进行赋值操作；而`b1=b++;`会先进行赋值操作，再进行自增操作。`c1=--c;`和`d1=d--;`也是如此。

为了强化记忆，我们再来看一个自增自减的综合示例：

```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a=12;
    int b=1;

    int c=a-(b--);  // ①
    int d=(++a)-(--b);  // ②

    printf("c=%d, d=%d\n", c, d);

    system("pause");
    return 0;
}
```

输出结果：

```
c=11, d=14
```

分析一下：

1\) 执行语句①时，会先进行`a-b`运算，结果是11，然后 b 再自减，就变成了 0，最后再将`a-b`的结果（也就是11）交给 c，所以 c 的值是 11。

2\) 执行语句②之前，b 的值已经变成 0。对于`d=(++a)-(--b)`，a 会先自增，变成 13，然后 b 再自减，变成 -1，最后再进行`13-(-1)`，结果是14，交给 d，所以 d 最终是 14。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/c/ji-chu/zi-589e28++29-he-zi-51cf28-29.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
