[英]Pre increment and post increment
我无法理解后增量( ++
),预增量( --
)和加法/减法如何在一个例子中协同工作。
x++
表示将1添加到变量中。
x--
表示从变量中减去1。
但我对这个例子感到困惑:
int x = 2, y = 3, z = 1;`
y++ + z-- + x++;
我假设这意味着3(+1) + 1(-1) + 2(+1)
这意味着结果应该是7。
但是当我编译它时,我得到6
。 我不明白。
int main() {
int x=2, y=3, z=1;
int result;
result = y++ + z-- + x++; //this returns 6
cout << result << endl;
return 0;
}
因为后缀operator++
在递增变量之前返回原始值。 前缀operator++
增加varialbe并返回对它的引用。 可以通过示例轻松说明该行为:
#include <iostream>
int main()
{
int n = 1;
std::cout << n++ << "\n"; // prints 1
std::cout << n << "\n"; // prints 2
int m = 10;
std::cout << "\n";
std::cout << ++m << "\n"; // prints 11
std::cout << m << "\n"; // prints 11
}
result = y++ + z-- + x++;
3 1 2 = 6
如果再次执行此操作
result1 = y++ + z-- + x++;
4 0 3 = 7
原因
operator++
在递增变量之前返回原始值。
和
++operator
返回递增的值
--
与上面相同的是它的减量
当你写x++
,它使用的当前值x
,然后由一个增加它。
如果你想先增加,你想写++x
。
Pre-increment operator(++p)
首先增加该值并赋值,然后post increment operator(p++)
首先赋值,然后执行增量运算。这里所有变量都是后增量,即它最初赋值(在缓冲区上)然后增加(对于y和x乘以1)并将z减小1.即最初在缓冲区中分配3 + 1 + 2(对缓冲区值执行加法)然后执行递增/递减,因为x = 3,y = 4且z = 0
有关更多信息,您可以阅读答案cout << c ++ << c ;?的正确答案是什么? 为什么这些构造(使用++)未定义的行为? 问题
原因很简单。 这里使用关联原则,它根据运算符的优先级计算值。
也是X++
或X--
表示......使用然后改变...它将首先使用该值并增加或减少它。 如果你想得到7
的输出......试试这个......它可能会起作用......
result = ++y + z-- + x++;
后增量/后增量将增加/减少变量,但会计算变量的“先前”值。
所以表达式result = y++ + z-- + x++
将表现得像:
result = y + z + x; // result == 6
// perform the 'post' operations
y += 1;
z -= 1;
x += 1;
但是,请记住,这必然是编译器执行评估的严格方式。 对于此表达式,结果已明确定义,您将在示例中结束。 在同一个表达式中使用多个递增/递减操作时,很容易将未定义的行为合并到您无法从表达式中特别期待的任何内容中。 请参阅为什么这些构造(使用++)未定义的行为? 详情。
i++
/ i--
是变量的后递增和递减...
所以在我们的表达式中,它将采用初始值来解决然后将inc / dec减1。
int x = 2, y = 3, z = 1;
y++ + z-- + x++;
2 + 3 + 1 = 6
您还可以通过while循环实现不同的行为:
#include <iostream>
void main{
int count = 0;
while (count < 5 )
{
std::cout << "counter is: " << count << std::endl
// replace this line with one of the lines below at a time
}
}
考虑的增量以下表达式count
++count // the variable 'count' will grow from 0 to 4
count++ // ditto, weird as it seems; 'count' grows nonetheless
count = ++count // the old 'count' becomes 'count + 1'
count = count++ // endless loop: back to square zero time and time again
同样,您可以使用带前缀的do-while循环获得更多洞察力
count = 0;
do
{
std::cout << ++count << "\n";
} while (count < 5); // prints out 1 to 5
与后缀相对
count = 0;
do
{
std::cout << count++ << "\n";
} while (count < 5); // prints out 0 to 4
Dim i As Integer = 10
Dim b As Integer
Dim c As Integer
Dim d As Integer
b = ++i
c = i + 1
d = b + c
Response.Write("<br/>")
Response.Write("The Value of ++i :-" & b)
Response.Write("<br/>")
Response.Write("The Value of i++ :-" & c)
Response.Write("<br/>")
Response.Write("Answer is " & d)
输出:
The Value of ++i :-10
The Value of i++ :-11
Answer is 21
这意味着++ var返回原始值,var ++返回递增值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.