++u or u++ which is faster?

D

David Hilsee

Filipe Valepereiro said:
Always use ++u, since they're suposed to be faster.
If you use iterator's then you must allways use ++u.
this is a recommendation from Bjarne Stroustrup book,
see chapter about Iterators
<snip>

If you're referring to the "advice" section, then let me point out that he
wisely uses the word "prefer" and not "always". In certain cases, favoring
preincrement leads to awkward code that isn't necessarily more efficient.
If you're going to wind up writing

SomeIterator tmp(i);
++i;
doSomething(tmp);
// no other usage of tmp after this

then you might as well write

doSomething( i++ );

This type of code most often occurs when iterating over certain containers
and erasing elements as you go.
 
D

David Hilsee

I understand why foo++ must return a copy of the old value if it is executed
at the beginning of the statement.
For example
bar( ++I );
is equivalent to
++I;
bar( I );
and
bar( I++ );
is equivalent to (J is temporary)
J = I++;
bar( J );
My question is why not evaluate I++ after bar() like this
Make
bar( I++ );
equivalent to
bar( I );
I++;

Of course, all this was decided long ago and nothing will be changed now.

That would make the operator behave differently from everything else. When
the programmer writes

bar( doSomething() );

that's supposed to mean that doSomething() executes, and its result is
passed to bar. Making the operator a special case would be confusing, IMHO,
especially if bar could determine the value of I (say, via a pointer). But
yes, all of this was decided long ago.
 
G

Guest

I couldn't understand the below sentence because I can't tell which of
the below should read u++ - could you fix it as I would really like to
keep my code efficient.

Plus, are you talking about built in types (eg int) or classes here?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,501
Latest member
Ledmyplace

Latest Threads

Top