assignment operator

what is the difference between a=a+1; and a++ or --a;

The difference is the generation of temporary objects. (Unless a is an integer type, which is likely specially optimized to avoid temporaries when possible.)
a=a+1 assigns the value of a+1 to a
a++ (post-increment) performs some action using the current value of a and then increments its value by 1
--a (pre-increment)reduces the current value of a by 1 and then allows a to perform some action
--a (pre-increment)


*--a (pre-DEcrement)

Sorry, couldn't resist.
For integer types these operators are basically the same, the assignment is overloaded so, that it passes by reference and no temporary objects are made or passed back. There is therefor no speed change, however a++ can be a easier to read at times. There is furthermore no change in the usage afterwards, except for the fact that you can actually determine when to in/decrement. The following code is therefor completely legit:
1
2
3
4
5
6
7
#include <iostream>

int main()
{
    int x = 0;
    std::cout << (x=6);
}
Note that if 'a' is not actually an integer, and is instead an object of type 'A', the 3 expressions above resolve to:
a++ => a.A::operator++(int);
--a => a.A::operator--();
a=a+1 => a.A::operator=( a.A::operator+(1) );

which could change behavior significantly, depending on the implementation of those methods.

--Rollie
As a general rule, the recommendation is to use pre-increment/decrement over post-increment/decrement
where it doesn't make a difference from a logic standpoint, as the (properly implemented) pre- operators
will always be at least as efficient, if not more efficient, than the post- operators.

For the same reason, if ++a is semantically equivalent to a = a + 1, then the same rule applies: prefer
the pre-increment version for efficiency reasons.

Yes, it looks "wrong" to write

++a;

over

a++;

but get used to the syntax.
@Nick Evan
*--a (pre-DEcrement)
yes of course.....got a bit carried away with my sermon!
@ jssmith
I have recently noted (in a text book i`m reading) that the pre-version is preferred over the post_version as you say/recommend even though there has been no specific attention drawn to it...so it must be as you say...the underlying efficiency which attends it.
Consider how a class would implement them, and then you'll see the performance difference:

1
2
3
4
5
6
7
8
9
10
11
12
struct Foo {
    Foo& operator++() { // pre-increment
        // do some work (same as below)
        return *this;
    }

    Foo operator++( int ) { // post-increment
        Foo tmp( *this );  // We return the unmodified object
        // do some work (same as above)
        return tmp;
    }
};


Notice there is (at least) one extra copy involved.
Topic archived. No new replies allowed.