Alex Rivera | Logout

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

Asked 2012-10-20T11:51:12.660
71

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?

Edit
Report

1 Answer

49

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. When used with 1 they mostly act as a prefix operation. 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:

first case (a++) (different)

(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)

(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)
   0x00000000
answered 2012-10-20T17:25:26.220

Your Answer