“++”之间的区别是什么?和“+ = 1”运营商? [英] What is the difference between "++" and "+= 1 " operators?
问题描述
在C ++的循环中,我通常遇到使用 ++
或 + = 1
不能告诉他们的区别。例如,如果我有一个整数
int num = 0;
,然后在循环中执行:
num ++;
或
num + = 1;
它们都会增加 num
的值,但是他们的区别是什么?我怀疑 num ++
可以工作得比 num + = 1
,但如何?这个差别是否微妙到足以被忽略?
num + = 1
所有这些表达式( num + = 1
,
num ++
和 ++ num
)递增 num
,但是 num ++
的值是 num
之前的 增加之前的值。 说明:
int a = 0;
int b = a ++; // now b == 0 and a == 1
int c = ++ a; // now c == 2 and a == 2
int d =(a + = 1); // now d == 3 and a == 3
使用任何你喜欢的。我更喜欢 ++ num
到 num + = 1
,因为它更短。
In a loop in C++, I usually encounter situations to use ++
or +=1
, but I can't tell their difference. For instance, if I have an integer
int num = 0;
and then in a loop I do:
num ++;
or
num += 1;
they both increase the value of num
, but what is their difference? I doubt num++
could work faster than num+=1
, but how? Is this difference subtle enough to be ignored?
num += 1
is rather equivalent to ++num
.
All those expressions (num += 1
, num++
and ++num
) increment the value of num
by one, but the value of num++
is the value num
had before it got incremented.
Illustration:
int a = 0;
int b = a++; // now b == 0 and a == 1
int c = ++a; // now c == 2 and a == 2
int d = (a += 1); // now d == 3 and a == 3
Use whatever pleases you. I prefer ++num
to num += 1
because it is shorter.
这篇关于“++”之间的区别是什么?和“+ = 1”运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!