C++ 增量和减量运算符

2024 年 8 月 28 日 | 3 分钟阅读

什么是 C++ 增量运算符的定义?

C++ 中的增量运算符是一个一元运算符。增量运算符用符号 (++) 表示。增量运算符将变量中记录的值加一。此运算符仅适用于数字。

C++ 增量运算符分为两种类型

  • 前置增量
  • 后置增量

1. 后置增量运算符 (a++)

后缀运算符表示应先使用值,然后再递增。这表示该值首先用于操作,然后由一更新。

C++ 代码

输出

The value before employing the post increment operator is: 7
The value held by temp is: 7
The result of applying the post increment operator is: 8

2. 前置增量运算符 (++a)

后缀运算符指定在使用之前递增该值。这表示该值在操作中递增一,然后由变量使用。

C++ 代码

输出

The value before employing the pre increment operator is: 7
The value held by temp is: 8
The result of applying the pre increment operator is: 8

C++ 减量运算符到底是什么?

C++ 中的减量运算符是一个一元运算符。增量运算符用符号 (-) 表示。减量运算符将变量的值减一。此运算符仅适用于数字。

C++ 减量运算符分为两种类型

  • 后置减量运算符
  • 前置减量运算符

1. 后置减量运算符 (a--)

后缀运算符表示应先使用值,然后再递减。这表示该值首先用于操作,然后由一减少。

C++ 代码

输出

The value before employing the post decrement operator is: 7
The value held by temp is: 7
The result of applying the post decrement operator is: 6

2. 前置减量运算符 (--a)

后缀运算符表示应在使用之前减少该值。这表示该值在操作中减少一,然后由变量使用。

C++ 代码

输出

The value before employing the pre decrement operator is: 7
The value held by temp is: 6
The result of applying the pre decrement operator is: 6