C/C中的增量前和增量后++

在C/C++中,增量运算符用于将变量的值增加1。此运算符由 ++ 象征增量运算符可以在将变量赋值之前将变量的值增加1,也可以在赋值之后将变量的值增加1。 因此,它可以分为两种类型:

null
  • 预增量运算符
  • 后增量运算符

1) 预增量运算符 :在表达式中使用变量之前,预增量运算符用于增加变量的值。在预增量中,值首先递增,然后在表达式中使用。

语法:

 a = ++x;

这里,如果“x”的值是10,那么“a”的值将是11,因为“x”的值在表达式中使用之前会被修改。

CPP

// CPP program to demonstrate pre increment
// operator
#include <iostream>
using namespace std;
// Driver Code
int main()
{
int x = 10, a;
a = ++x;
cout << "Pre Increment Operation" ;
// Value of a will change
cout << "a = " << a;
// Value of x change before execution of a=++x;
cout << "x = " << x;
return 0;
}


输出

Pre Increment Operationa = 11x = 11

2) 后增量运算符 :在完全执行使用后增量的表达式后,后增量运算符用于增加变量的值。在增量后处理中,值首先在表达式中使用,然后递增。

语法:

 a = x++;

这里,假设“x”的值是10,那么变量“a”的值将是10,因为使用了“x”的旧值。

CPP

// CPP program to demonstrate post increment
// operator
#include <iostream>
using namespace std;
// Driver Code
int main()
{
int x = 10, a;
a = x++;
cout << "Post Increment Operation" ;
// Value of a will not change
cout << "a = " << a;
// Value of x change after execution of a=x++;
cout << "x = " << x;
return 0;
}


输出

Post Increment Operationa = 10x = 11

后增量运算符的特殊情况: 如果我们将递增后的值分配给同一个变量,那么该变量的值将不会递增,也就是说,它将保持与之前相同的状态。

语法:

a = a++;

这里,如果“x”的值是10,那么“a”的值将是10,因为“x”的值被分配给“x”的后增量值。

C++

// CPP program to demonstrate special
// case of post increment operator
#include <iostream>
using namespace std;
int main()
{
int x = 10;
cout << "Value of x before post-incrementing" ;
cout << "x = " << x;
x = x++;
cout << "Value of x after post-incrementing" ;
// Value of a will not change
cout << "x = " << x;
return 0;
}


输出:

Value of x before post-incrementingx = 10Value of x after post-incrementingx = 10

注: 这种特殊情况仅适用于后增量和后减量运算符,而预增量和预减量运算符在这种情况下工作正常。

同时评估岗位和增薪前

postfix++的优先级比prefix++高,它们的关联性也不同。前缀++的关联性是从右到左,后缀++的关联性是从左到右。

  • postfix++的关联性是从左到右的
  • 前缀++的关联性是从右向左的

本文由 苏维克·南迪 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享