TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Bill Birrell
from: Darin McBride
date: 2004-04-12 20:41:48
subject: Squares

Hello Bill!

Replying to a message of Bill Birrell to Neil Heller:

 >> That bring up an interesting point.  It is such a
 >> common thing to
 >> compare the loop counter to a result involving the
 >> loop counter in some
 >> sort of function

 >>        (ie:  (for n=0; n> that I would consider it only natural that any
 >> optimizing compiler would
 >> do what you did, only automatically.  Is this the
 >> case?  Or should I be
 >> concerned with optimizing manually - not trusting the
 >> compiler
 >> manufacturer?

As has already been mentioned, the general case says that
"target" can change: target may not be const, or what it points
at may not be const.  I would wager that most modern compilers could
optimise:

#define STRING "hello world\n"
int n;
for (n = 0; n < strlen(STRING); n++) { /* ... */ }

But if target can be moving (a moving target?), pointing at different
strings in each iteration, or perhaps target ends up getting a nul char put
in it during some iteration, there's really no easy way to optimise it.

 BB>     I wouldn't rely on it happening automatically, Neil. It's actually
 BB> a little more than an optimization. It's a real change in the program
 BB> to eliminate a needless bottleneck. I'm not sure optimizers are
 BB> allowed to take such liberties. I'd check with one of our resident
 BB> gurus, like Bob Stout or Darren McB.

The last time I programmed in C or C++ would have been two or three years ago :-(

 BB>     OTOH you can check for yourself by compiling both programs, each
 BB> with a slightly different name, and then check the execution times.
 BB> That would be a practical and pragmatic way to be sure of what your
 BB> own favourite compiler does.

Well, that can be somewhat painful.  Depending on your skill with assembly,
you may want to compile both programs and get the assembler for it, and
look at that, it may show you what instructions are used.  While this isn't
exactly a 100% fool-proof method, either (different instructions take
different numbers of clock cycles), it's usually reasonably safe to assume
that more instructions take longer than fewer instructions, especially when
you're comparing hand optimised vs non-optimised code that is intended to
do the same thing.

I would always suggest that if you're dealing with a constant, mark it as
such.  Don't allow some poor compiler coder get it wrong.  Oh, and better
yet, don't allow the reader of your code to get confused ;-)

Darin

---
* Origin: Tanktalus' Tower BBS (1:250/102)
SEEN-BY: 633/267 270
@PATH: 250/102 99 10/345 106/1 2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.