[mythtv] C++ style

Paul Woodward paul_woodward at fastnet.co.uk
Wed Feb 11 14:50:46 EST 2004


> On Wed, 11 Feb 2004, Paul Woodward wrote:
> 
> > > On Wednesday 11 February 2004 13:25, steve at nexusuk.org wrote:
> > > > On Wed, 11 Feb 2004, John P. Poet wrote:
> > > > > For example, he says to always use pre-decrement/increment instead
> > > > > of post-decrement/increment -- when possible.  The "pre" versions
> > > > > can be converted into more efficient assembly language code, than
> > > > > the "post" versions.  The only time you should use the "post"
> > > > > version, is when you really need the increment/decrement to happend
> > > > > after the *current* value of the variable has been used in the
> > > > > expression.
> > > >
> > > > I would hope the optimizer on the compiler would optimize correctly,
> > > > afterall, it's not hard for the optimizer to spot that you're not
> > > > assigning the value to anything (in which case it doesn't matter if
> > > > you do post or pre, so the optimizer can pick the fastest).
> > >
> > > That's only half true.  pre/post inc/decrement is also significant in
> > > non-assignment expressions, like "if" conditions.  In fact, the only
> > > time I can think of where it doesn't matter is if it's in it's own
> > > statement by itself, with no assignment, like:
> > >
> > > 	foo++;
> > > is equivalent to
> > > 	++foo;
> > > or
> > > 	for (int i = someval; i < someotherval; i++)
> > > is equivalent to
> > > 	for (int i = someval; i < someotherval; ++i)
> > >
> > > but
> > > 	if (somevar == ++i)
> > > is definitely different than
> > > 	if (somevar == i++)
> > >
> >
> > I don't think even Microsoft could come up with up with a compiler that
> >  generates such poor code that it takes a significant time to INC a
> >  register on an nGhz chip!
> 
> True.  A post operation does incure the extra over-head of saving the
> current value of the variable, before doing the operation.  The question
> raised though, is the compiler smart enough to NOT save the current value
> when it is not actually needed?
> 

I accept that ++ and other operators can be overloaded and that creates a whole new problem. In the simple case however, I am strongly of the view that code should be written primarily to be clear, concise and legible. Defensive coding is a very good idea indeed. Speed and optimisations IMHO should be the last thought of any programmer working on software that is in a 'developing' state.

These days it costs far less to buy a faster machine than the cost in terms of human time as a result of trying to debug some 'clever' code. Obviously I'm not justifying or advocating bad code, but there has to be a balance.

Just my 2p.



More information about the mythtv-dev mailing list