++x vs x++

My instructors never really explained when one or the other would be more efficient...

I always code x++

Is there any time or situation ++X would be better? If so, why?
++x is faster if you are doing it on a single line, since ++x doesn't have to a create a temporary. (Although I think all compilers will optimize that away anyway) If you are doing it in the middle of the line, it depends on what you are doing, since ++x and x++ have different meanings.
Last edited on
closed account (jwC5fSEw)
++x increments x and returns the incremented number, whereas x++ returns x and then increments it.
For objects with overloaded operators, always use pre-increment (++x), it's (supposedly) faster.

Edit:
Unless, of course, you want to get the current value of x and then increment it. The two have totally different semantics when used in assignment, e.g.
1
2
3
4
int x = 5,
    y = x++, /* y = 5 */
    z = ++x; /* z = 7 */
    /* x = 7 */
Last edited on
The easiest rule to remember is always use ++x (or --x) regardless of the type of x unless you absolutely
need post-increment (post-decrement), since pre will never be more expensive than post.

It's surprising how rarely you will actually see someone doing it right... As posted above, though, it's typically optimized away in the simple case anyway.

Here's an example from the X Toolkit Intrinsics Reference Manual:
1
2
3
4
5
6
7
8
Arg args[20];
int n;

n = 0;
XtSetArg( args[n], XtNheight, 100 ); n++;
XtSetArg( args[n], XtNwidth,  200 ); n++;
// etc.
XtSetValues( widget, args, n  );


To remember which one is preferred, just imagine how you would implement them.
Last edited on
Where does

1
2
 x+=1;


fit into this? Would it be better to do this to avoid possible ambiguity (what chrisname posted) ? And how does it compare to x++ and ++x in terms of speed?
XtSetArg( args[n], XtNheight, 100 ); n++;
Odd. Why not just XtSetArg( args[n++], XtNheight, 100 );? Seems a bit clearer to me than leaving two statements in the same line.

x+=1 has the exact same meaning as ++x, but it may compile to slightly different code under different circumstances.
Last edited on
I think it's safe to assume most programmers will understand ++x or x++; if not, they can go find out what it is.

@helios,
I can't really think of a case where the way it's written is better, except where they decide to change the prototype for XtSetArg to use n twice, and even then, they could just increment it the second time they use it. I guess the developers just thought it looked neater, or more "right"...
Last edited on
That is because XSetArg() is often a macro.
Topic archived. No new replies allowed.