Help me with Concatenating strings

F

Frederick Gotham

Thomas J. Gritzan posted:
However, a simple compare of two variables that are already stored in
registers won't do any damage.


Of course it will, several million femtoseconds in fact.

A buffer overflow caused by a superfluous and redundant check,
sacrificed for a few microseconds, will do damage.


Indeed, which is why on would be wise to destory the possibility.
 
C

Chris Torek

If you tell John to drive your car past the neighbouring town to drop it
into the mechanic, don't just sit back and expect him to take the shorter
route up past the old cemetary -- explicitly instruct him to do so.

Well, there are shortcuts, and then there is "make sure you tell
John not to go from your house to your neighbor's on the west by
going 24,000 miles east"... :)
When you write:

for(size_t i = 0; max != i; ++i) /* Body */

you're *explicitly* telling the compiler that the conditional must be
evaluated before the first iteration. Of course, in accordance with the "as
if" principle, the compiler may elide the first evaluation if it realises
that it's utterly redundant (just like John _might_ take the quicker
route).

There are really only three "interesting" cases for this code:

a) max is a constant.
b) max is a variable, and might be zero, and if it is zero the
loop must not run.
c) max is a variable, and guaranteed not to be zero.

In case (a), a compiler that fails to optimize away a "test at
top of loop" is the moral equivalent of the guy who goes 24,000
miles east so as to wind up half a block west.

In case (b), the test at the top is needed. Omitting it makes the
code incorrect.

In general, then, only case (c) is worth worrying about -- and if
that test at the top is truly significant, the loop may well need
to be special-cased and/or unrolled or otherwise handled in a
fancier fashion than this:
If you _don't_ want the conditional to be evaluated for the first
iteration, then simply TELL the compiler:

size_t i = p;

do /* Body */
while(max != ++i);

[I assume this was meant to read "size_t i = 0;".]

The do-while form is *most* appropriate (not "only", but "most") when
the loop has to run at least once even if whatever condition is to be
tested is true initially.
There's micro-optimisation, and then there's wanton sabotage of the
efficiency of one's code by being lax and saying "Hey compiler, just get
the job done however you like, I'm not too pushed whether it's efficient or
not."

And then there's "cluttering up the source code with repetitive
instructions not to drive 24,000 miles the wrong way"... :)
 

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

Members online

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top