简体   繁体   English

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

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

In a loop in C++, I usually encounter situations to use ++ or +=1 , but I can't tell their difference.在 C++ 的循环中,我通常会遇到使用+++=1的情况,但我无法分辨它们的区别。 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?它们都增加了num的值,但它们有什么区别? I doubt num++ could work faster than num+=1 , but how?我怀疑num++能否比num+=1工作得更快,但如何呢? Is this difference subtle enough to be ignored?这种差异是否细微到可以忽略?

num += 1 is rather equivalent to ++num . num += 1相当于++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.所有这些表达式( num += 1num++++num )都会将num的值递增 1,但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 ++num to num += 1 because it is shorter.我更喜欢++num而不是num += 1因为它更短。

prefix and postfix operations 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 .当与1一起使用时,甚至可能会说它们是多余的。 When used with 1 they mostly act as a prefix operation.当与1一起使用时,它们主要充当前缀操作。 In fact on my machine they produce the same machine code.事实上,在我的机器上,它们生成相同的机器代码。 You can try this by using an example program such as:您可以使用示例程序来尝试此操作,例如:

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 gdb which 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   $0x0,-0x8(%rbp)
   0x00000000004004bf <+11>:    mov    -0x8(%rbp),%eax
   0x00000000004004c2 <+14>:    mov    %eax,-0x4(%rbp)
   0x00000000004004c5 <+17>:    addl   $0x1,-0x8(%rbp)
   0x00000000004004c9 <+21>:    pop    %rbp
   0x00000000004004ca <+22>:    retq
End of assembler dump.

second case ( ++a )第二种情况( ++a

(gdb) disassemble foo
Dump of assembler code for function foo:
   0x00000000004004b4 <+0>:     push   %rbp
   0x00000000004004b5 <+1>:     mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     movl   $0x0,-0x8(%rbp)
   0x00000000004004bf <+11>:    addl   $0x1,-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.

third case ( a += 1 )第三种情况( a += 1

(gdb) disassemble foo
Dump of assembler code for function foo:
   0x00000000004004b4 <+0>:     push   %rbp
   0x00000000004004b5 <+1>:     mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     movl   $0x0,-0x8(%rbp)
   0x00000000004004bf <+11>:    addl   $0x1,-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.

fourth case ( a = a + 1 )第四种情况( a = a + 1

(gdb) disassemble foo
Dump of assembler code for function foo:
   0x00000000004004b4 <+0>:     push   %rbp
   0x00000000004004b5 <+1>:     mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     movl   $0x0,-0x8(%rbp)
   0x00000000004004bf <+11>:    addl   $0x1,-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.

As you can see they produce the same machine code even without compiler optimizations turned on except the first case which has addl after mov s.正如您所看到的,即使没有打开编译器优化,它们也会生成相同的机器代码,除了第一种情况,它在mov之后有addl This means that you should be using whichever you like as a user and let the compiler guys do the rest.这意味着您应该使用任何您喜欢的用户,让编译器人员完成剩下的工作。

And lastly, note that cousin operators *= and /= have no postfix and prefix counterparts.最后,请注意表亲运算符*=/=没有对应的后缀前缀

The ++ prefix or postfix operators change the variable value. ++前缀或后缀运算符更改变量值。

int a = 0;
int b = a++; // b is equal to 0, a is equal to 1

Or prefix:或前缀:

int a = 0;
int b = ++a; // b = 1, a = 1

If used like this, they are the same:如果像这样使用,它们是相同的:

int a = 0;
++a; // 1
a++; // 2
a += 1; // 3

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第一种情况——后自增运算符

int n=5;
int new_var;

new_var=n++;

print("%d",new_var);

Output=5输出=5

Second Case第二个案例

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

Output =6输出=6

This is very similar to what pre-increment operator would result in.这与预增量运算符的结果非常相似。

Second Case using Pre-increment operator使用预增量运算符的第二种情况

int n=5;

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

Output =6输出=6

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.对于原始类型(指针、整数等),它们都将值递增 1。 But, for C++ classes, they call different operators ( operator+= vs. operator++ );但是,对于 C++ 类,它们调用不同的运算符( operator+=operator++ ); indeed, for some classes, like list<T>::iterator , i += 1 does not work and i++ must be used.实际上,对于某些类,例如list<T>::iteratori += 1不起作用,必须使用i++

Furthermore, they produce different values.此外,它们产生不同的价值。 i += 1 produces i after incrementing (like a preincrement), while i++ produces i before incrementing. i += 1在递增之后产生i (类似于预递增),而i++在递增之前产生i Thus,因此,

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

prints 1 0 .打印1 0 Because i += 1 is equivalent to a preincrement, in some cases, i += 1 may result in different behaviour than i++ .因为i += 1等同于预增量,所以在某些情况下, i += 1可能导致与i++不同的行为。

So, while they are the same for incrementing variables, one should be aware that they are not perfect substitutes in all conditions.因此,虽然它们对于递增变量是相同的,但应该意识到它们并不是在所有情况下的完美替代品。

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例如,a+=1 编译为汇编是
add a,1添加一个,1
and a++ or ++a is而 a++ 或 ++a 是
inc a公司
There may be some mildly difference in efficiency because they are two different CPU operation.由于它们是两个不同的 CPU 操作,因此效率可能略有不同。

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. preincrement 和 postincrement 运算符旨在用于 INSIDE EXPRESSIONS 以在变量值用于包含它的任何表达式之前或之后更改变量值。 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.使用后增量运算符时,变量的旧值用于计算封闭表达式,并且仅在此之后变量才会递增。

For example:例如:

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

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:但是,如果您这样做:

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.

I am surprised noone mentions that at least for old compilers / computers (basically when C was born and a decade or two after) += 1 will be significantly slower than ++ .令我惊讶的是,没有人提到至少对于旧的编译器/计算机(基本上是在 C 诞生时以及之后的一两年) += 1++慢得多。 ++ is an increment which the CPU most likely has a single instruction for. ++是 CPU 最有可能有一条指令的增量。 += 1 requires loading the value 1 into a register (likely saving the value of it... somewhere) and calling for an addition. += 1需要将值 1 加载到寄存器中(可能会保存它的值......某处)并调用加法。 I can't say whether current compilers optimize this out but I suspect they do.我不能说当前的编译器是否优化了这一点,但我怀疑他们这样做了。

I'm new to Stackoverflow but here's my 2 pence worth.我是 Stackoverflow 的新手,但这是我的 2 便士价值。

If the question is about += and not +=1.如果问题是关于 += 而不是 +=1。 The statement posted was;发表的声明是;

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。例如:

// 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

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.希望这是有用的。

++ is used to increment value by 1, while using += you can increment by another amount. ++ 用于将值递增 1,而使用 += 可以递增另一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM