0

so I am looking at the following snippet of code

int a = 3;
int b = 2;
b = a++;
cout << ++b;

My understanding line by line is:

  1. initiate a = 3
  2. initiate b = 2;
  3. assign the value of (a+1) to b, so b = 4;
  4. print b+1, which is 5.

However this is wrong, can someone explain this in simple terms? I am new to C++

Hbi Giu
  • 113
  • 1
  • 9
  • 6
    You are confusing pre-increment and post-increment. `a++` and `++a` are not the same. Related: http://stackoverflow.com/questions/4445706/post-increment-and-pre-increment-concept – Fabio says Reinstate Monica Aug 03 '16 at 21:09

3 Answers3

4

In the statement:

b = a++

a is evaluated for the assignment to b and after that a is then incremented so a = a+1.

On the other hand:

b = ++a

Increments a so a = a+1 before a is then evaluated for assignment to b.

You can look deeply here:

Pre-increment or post-increment in C/C++

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
3

In C++ when an increment or decrement is used in an expression, the position of "++" or "--" matters. If the operator is before a variable then the increment or decrement will be done before the end of the expression, in the opposite situation the increment or decrement will be done after the entire expression is executed.

int b = ++a; // first add +1 to a, then assign a to b
int b = a++; // assign a to b, then add +1 to a
reckless
  • 741
  • 12
  • 53
2

Here you go:

  • initiate a = 3
  • initiate b = 2;
  • assign the value of (a) to b, so b = 3 and increment a to 4;
  • print b+1, which is 4.
Steephen
  • 14,645
  • 7
  • 40
  • 47