什么时候在C ++中使用i ++或++ i?

递增运算符用于将值增加一,而递减相反。减量运算符将值减一。

预递增(++ i) -在将值分配给变量之前,将值递增1。

后递增(i ++) -将值分配给变量后,值将递增。

这是C ++语言中i ++和++ i的语法,

++variable_name; // Pre-increment
variable_name++; // Post-increment

这里,

variable_name-用户给定的变量名。

这是C ++语言中前后递增的示例,

示例

#include <iostream>
using namespace std;
int main() {
   int i = 5;
   cout << "The pre-incremented value: " << i;
   while(++i < 10 )
   cout<<"\t"<<i;
   cout << "\nThe post-incremented value: " << i;
   while(i++ < 15 )
   cout<<"\t"<<i;
   return 0;
}

输出结果

The pre-incremented value: 56789
The post-incremented value: 101112131415

在以上程序中,main()函数中存在前后递增的代码。将整数类型的变量i递增,直到i的值小于10,然后递增,直到i的值小于15。

while(++i < 10 )
printf("%d\t",i);
cout << "\nThe post-incremented vaue : " << i;
while(i++ < 15 )
printf("%d\t",i);