C++ “++”和“+= 1”运算符有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12988140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:50:38  来源:igfitidea点击:

What is the difference between "++" and "+= 1 " operators?

c++loopsintegerauto-incrementincrement

提问by E_learner

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

在 C++ 的循环中,我通常会遇到使用++or 的情况+=1,但我无法分辨它们的区别。例如,如果我有一个整数

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,但它们的区别是什么?我怀疑num++可以比 更快地工作num+=1,但是如何?这种差异是否足够微妙以至于可以忽略?

回答by Alexandre C.

num += 1is rather equivalent to ++num.

num += 1相当于++num.

All those expressions (num += 1, num++and ++num) increment the value of numby one, but the value of num++is the value numhad beforeit got incremented.

所有这些表达式(num += 1num++++num)增加值num的一个,但价值num++是值num之前它得到了增加。

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 ++numto num += 1because it is shorter.

使用任何你喜欢的东西。我更喜欢++numnum += 1因为它更短。

回答by none

prefixand postfixoperations are perfect candidates for exam questions.

前缀后缀操作是考试题目的完美候选。

a = 0;
b = a++;  // use the value and then increment --> a: 1, b: 0

a = 0;
b = ++a;  // increment and then use the value --> a: 1, b: 1

+=operation and its sister -=are more general solutions mostly intended to be used with different numbers. One might even say they are redundant when used with 1. When used with 1they mostly act as a prefixoperation. In fact on my machine they produce the same machine code. You can try this by using an example program such as:

+=operation 和它的姐妹-=是更通用的解决方案,主要用于不同的数字。人们甚至可能会说它们在与1. 当与1它们一起使用时,它们主要用作前缀操作。事实上,在我的机器上,它们产生相同的机器代码。您可以通过使用示例程序来尝试此操作,例如:

void foo() {
    int a, b;
    a = 0;

    // use one of these four at a time
    b = a++;          // first case (different)
    b = ++a;          // second case
    b = (a += 1);     // third case
    b = (a = a + 1);  // fourth case
}

int main() {
    foo();
    return 0;
}

and disassembling in gdbwhich would give:

并拆卸gdb其中将给出:

first case (a++) (different)

第一种情况 ( a++) (不同)

(gdb) disassemble foo
Dump of assembler code for function foo:
   0x00000000004004b4 <+0>:     push   %rbp
   0x00000000004004b5 <+1>:     mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     movl   
(gdb) disassemble foo
Dump of assembler code for function foo:
   0x00000000004004b4 <+0>:     push   %rbp
   0x00000000004004b5 <+1>:     mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     movl   
(gdb) disassemble foo
Dump of assembler code for function foo:
   0x00000000004004b4 <+0>:     push   %rbp
   0x00000000004004b5 <+1>:     mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     movl   
(gdb) disassemble foo
Dump of assembler code for function foo:
   0x00000000004004b4 <+0>:     push   %rbp
   0x00000000004004b5 <+1>:     mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     movl   
int a = 0;
int b = a++; // b is equal to 0, a is equal to 1
x0,-0x8(%rbp) 0x00000000004004bf <+11>: addl
int a = 0;
int b = ++a; // b = 1, a = 1
x1,-0x8(%rbp) 0x00000000004004c3 <+15>: mov -0x8(%rbp),%eax 0x00000000004004c6 <+18>: mov %eax,-0x4(%rbp) 0x00000000004004c9 <+21>: pop %rbp 0x00000000004004ca <+22>: retq End of assembler dump.
x0,-0x8(%rbp) 0x00000000004004bf <+11>: addl
int a = 0;
++a; // 1
a++; // 2
a += 1; // 3
x1,-0x8(%rbp) 0x00000000004004c3 <+15>: mov -0x8(%rbp),%eax 0x00000000004004c6 <+18>: mov %eax,-0x4(%rbp) 0x00000000004004c9 <+21>: pop %rbp 0x00000000004004ca <+22>: retq End of assembler dump.
x0,-0x8(%rbp) 0x00000000004004bf <+11>: addl
int n=5;
int new_var;

new_var=n++;

print("%d",new_var);
x1,-0x8(%rbp) 0x00000000004004c3 <+15>: mov -0x8(%rbp),%eax 0x00000000004004c6 <+18>: mov %eax,-0x4(%rbp) 0x00000000004004c9 <+21>: pop %rbp 0x00000000004004ca <+22>: retq End of assembler dump.
x0,-0x8(%rbp) 0x00000000004004bf <+11>: mov -0x8(%rbp),%eax 0x00000000004004c2 <+14>: mov %eax,-0x4(%rbp) 0x00000000004004c5 <+17>: addl
int n=5;
n+=1;
new_var=n;
print("%d",new_var);
x1,-0x8(%rbp) 0x00000000004004c9 <+21>: pop %rbp 0x00000000004004ca <+22>: retq End of assembler dump.

second case (++a)

第二种情况 ( ++a)

int n=5;

new_var=++n;
print("%d",new_var);

third case (a += 1)

第三种情况(a += 1

i = 10;
j = i++;  // This causes j to be 10 while i becomes 11.

fourth case (a = a + 1)

第四种情况(a = a + 1

i = 10;
j = ++i; // Now both i and j will be 11 because the increment
         // of i occurs PRE (BEFORE) its value is used in the greater expression.

As you can see they produce the same machine code even without compiler optimizations turned on except the first case which has addlafter movs. This means that you should be using whichever you like as a user and let the compiler guys do the rest.

正如您所看到的,即使没有打开编译器优化,它们也会生成相同的机器代码,除了第一种addlmovs之后的情况。这意味着您应该使用任何您喜欢的用户,让编译器人员完成剩下的工作。

And lastly, note that cousin operators *=and /=have no postfixand prefixcounterparts.

最后,请注意表亲运算符*=/=没有后缀前缀对应物。

回答by dreamzor

The ++prefix or postfix operators changethe variable value.

++前缀或后缀运算符改变变量值。

int a = 0, b = 0;
cout << (a+=1) << " " << b++ << endl;

Or prefix:

或前缀:

// Example 1:
num = 0;
num = ++;
// the result of num will be 1

// Example 2:
num = 0;
num = += 1;
// the result of num will be 1 the same as example 1

// Example 3:
num = 0;
num = += 2;
// the result of num will be 2.

// Example 4:
num = 0;
num = ++ 2;
// this would not compile as ++ will not except any value for the increment step it is assumed
// you will always want to increment by the value of 1

If used like this, they are the same:

如果像这样使用,它们是相同的:

##代码##

回答by Desert Ice

Both the operators increase the value of n by 1. The difference between them exists when you use the operators along with the assignment operator.

这两个运算符都将 n 的值增加 1。当您将这些运算符与赋值运算符一起使用时,它们之间存在差异。

For example:

例如:

First Case--Post-Increment operator

第一种情况--Post-Increment 运算符

##代码##

Output=5

输出=5

Second Case

第二种情况

##代码##

Output =6

输出=6

This is very similar to what pre-increment operator would result in.

这与预增量运算符的结果非常相似。

Second Case using Pre-increment operator

使用预增量运算符的第二种情况

##代码##

Output =6

输出=6

回答by bigfish

They are generally the same and there is no significance to clarify the difference between them. But the implementing of these two statement are in fact different. For example, a+=1 compiling to assember is
add a,1
and a++ or ++a is
inc a
There may be some mildly difference in efficiency because they are two different CPU operation.

它们大体上是相同的,澄清它们之间的区别没有意义。但是这两个语句的实现实际上是不同的。例如a+=1编译成汇编是
加a,1
和a++或++a是
inc a
效率上可能会有一些轻微的差异,因为它们是两种不同的CPU操作。

回答by Tom Wetmore

Some of you are approaching the difference, but it should be stated very clearly:

你们中的一些人正在接近差异,但应该非常清楚地说明:

THEY ARE VERY DIFFERENT OPERATORS.

他们是非常不同的运营商。

The preincrement and postincrement operators are designed to be used INSIDE EXPRESSIONS to change the value of the variable either BEFORE or AFTER the value of the variable is used in whatever expression encloses it. When using the postincrement operator the OLD value of the variable is used to evaluate the enclosing expression and only after that is the variable incremented.

preincrement 和 postincrement 运算符被设计为在内部表达式中使用来更改变量的值,无论是在变量值用于包含它的任何表达式中之前还是之后。使用后增量运算符时,变量的 OLD 值用于计算封闭表达式,只有在此之后变量才会递增。

For example:

例如:

##代码##

This is why it is called the postincrement operator. The variable is incremented POST (AFTER) it's value is used in the greater expression (here an assignment expression).

这就是它被称为后增量运算符的原因。变量在 POST (AFTER) 后递增,它的值用于更大的表达式(这里是赋值表达式)。

However, if you do:

但是,如果您这样做:

##代码##

回答by nneonneo

These two operators may appear to be similar, but they are quite different.

这两个运算符可能看起来很相似,但它们却大不相同。

For primitive types (pointers, integers, etc.) they both increment the value by one. But, for C++ classes, they call different operators (operator+=vs. operator++); indeed, for some classes, like list<T>::iterator, i += 1does not work and i++must be used.

对于原始类型(指针、整数等),它们都将值加一。但是,对于 C++ 类,它们调用不同的运算符(operator+=vs. operator++);确实,对于某些类,例如list<T>::iteratori += 1不起作用,i++必须使用。

Furthermore, they produce different values. i += 1produces iafter incrementing (like a preincrement), while i++produces ibefore incrementing. Thus,

此外,它们产生不同的值。在递增后i += 1产生i(如预递增),而在递增前i++产生i。因此,

##代码##

prints 1 0. Because i += 1is equivalent to a preincrement, in some cases, i += 1may result

打印1 0。因为i += 1相当于一个预增量,在某些情况下,i += 1可能会导致

So, while they are the same for incrementing variables, one should be aware that they are not perfect substitutes in all conditions.

因此,虽然它们对于递增变量是相同的,但应该意识到它们并不是所有条件下的完美替代品。

回答by Kevin Morrissey

I'm new to Stackoverflow but here's my 2 pence worth.

我是 Stackoverflow 的新手,但这是我的 2 便士。

If the question is about += and not +=1. The statement posted was;

如果问题是关于 += 而不是 +=1。发表的声明是;

I usually encounter situations to use ++ or +=1, but I can't tell their difference.

我通常会遇到使用 ++ 或 +=1 的情况,但我无法分辨它们的区别。

I think the 1 could just have easily been another number or perhaps better written as +=?

我认为 1 可以很容易地成为另一个数字,或者更好地写成 +=?

In terms of the result there is no difference (using the posters values). Both will increment by one, however, ++ will only increment by 1 whereas += will increment by the value specified by the coder, in ederman's example this happens to be 1. For Example:

就结果而言,没有区别(使用海报值)。两者都会增加 1,但是,++ 只会增加 1,而 += 会增加编码器指定的值,在 ederman 的例子中,这恰好是 1。例如:

##代码##

So if you only want to increment a value by 1 I would use ++ but if you need to increment by more the 1 use +=

因此,如果您只想将值增加 1,我会使用 ++ 但如果您需要增加更多的 1 使用 +=

Hope that is useful.

希望这是有用的。

回答by chx

I am surprised noone mentions that at least for old compilers / computers (basically when C was born and a decade or two after) += 1will be significantlyslower than ++. ++is an increment which the CPU most likely has a single instruction for. += 1requires loading the value 1 into a register (likely saving the value of it... somewhere) and calling for an addition. I can't say whether current compilers optimize this out but I suspect they do.

我很惊讶没有人提到至少对于旧的编译器/计算机(基本上是在 C 诞生时和十年或两年之后)+= 1明显慢于++. ++是 CPU 最有可能有一条指令的增量。+= 1需要将值 1 加载到寄存器中(可能将它的值保存在...某处)并调用一个加法。我不能说当前的编译器是否对此进行了优化,但我怀疑他们这样做了。

回答by Alfa3eta

++ is used to increment value by 1, while using += you can increment by another amount.

++ 用于将 value 增加 1,而使用 += 您可以增加另一个数量。