When to use ++x and x++?

I'm not really sure what's happening here and when 1 is being added to each variable. I was wrote this to try to understand it but i'm still confused. Can someone please explain whats happening.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main()
{
    int y = 2;
    int x = y++;
    cout << x << endl;  //prints 2
    ++x;
    cout << x << endl;   //prints 3
    return 0;
}



Thank you :)
The post increment shown on line 7 basically resolves to:

This is post increment:
1
2
3
    int tmp = y;
    y++;
    int x = tmp;


pre increment doesn't need the temporary variable: it increments and returns the incremented value.

I suggest to use the increment operator on it's own
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int x = 2;
    int y = x++; // Takes the Cuurent value of x assignes it to y and then increments x
    int z = ++x; // Increments x and then assignes the new value to z

    cout << "x = " << x << endl
         << "y = " << y << endl
         << "z = " << z << endl;  

    return 0;
}
And by the way...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
for (int i=0; i < n; i++)
    doSomething();

// is the same as

int i=0;

while (i < n)
{
    doSomething();
    i++;
}

// which is the same as

int i=0;

while (i < n)
{
    doSomething();
    ++i;
}

// which is the same as

for (int i=0; i < n; ++i)
    doSomething();


Conclusion: use ++counter instead of counter++ in for() loops.
http://stackoverflow.com/questions/4706199/post-increment-and-pre-increment-in-for-loop
ok thanks heaps :)
Conclusion: use ++counter instead of counter++ in for() loops.
How is this the conclusion for the premise that they're equivalent?
Generally speaking, if only used in a single term expression, the prefix increment operator is preferred because it has less overhead to its use. That being said, the increased efficiency of ++i over i++ is quite small. In the examples of the for loops increment expression, both perform exactly the same logically speaking. The real concerns are when they are used in multi-term expressions and statements as shown above.
Last edited on
How is this the conclusion for the premise that they're equivalent?

Heh. I totally forgot to point out that prefix is sometimes faster.
http://www.parashift.com/c++-faq/increment-pre-post-speed.html
Topic archived. No new replies allowed.