TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Jasen Betts
from: Darin McBride
date: 2004-04-17 20:15:18
subject: Squares

Hello Jasen!

Replying to a message of Jasen Betts to Bill Birrell:

 JB> Hi Bill.

 JB> 15-Apr-04 10:23:03, Bill Birrell wrote to Darin McBride


 JB>>>> and possibly even better re-written to use a char* instead

 JB>>>>  for( s=target ; *s ; s++ ) {

 >>> Yes, I like this even more ;-)

 BB>>     Not much point in using a for(;;) loop at all then. Why not
 BB>> just:-

 BB>>     char *s=target;
 BB>>     while(*s++) {...};

 BB>>     simpler, neater, more direct.

 JB> but not equivalent.

Good catch!

 JB>   char *s=target-1;
 JB>   while(*++s) {...};

Not supported by the standard ;-)

char* s = target;

if (*s != '\0')
{
  do {
    ...
  } while (*++s);
}

The problem with yours is that if target was, for example, pointing to
address 0x00000001, when you subtracted 1, it may not work.  Now, before
any of the technical gurus attack me for breaking the standard just as much
as I just complained about, I just want to say that this is only intended
to get a point across.  In reality, subtracting 1 from 0x00000001 may work
(an address of 0x00000000 is not necessarily the same as NULL).  However,
I'm sure anyone who didn't see the problem with Jasen's original code would
have missed this problem, too ;-)

Unfortunately, I'm not sure that there is a more real example.  All I know
is that the standard does not guarantee what happens when you point to
memory that is not given to you by the compiler (either by saying
char*s="foo" or taking the address of something on the stack, or
from the return of malloc or any other allocating routine).  Even if you
don't dereference it.

So, you can't simply decrement and increment and expect things to work
perfectly across all conforming environments (generally speaking, an
"environment" will be a compiler, but, again, nothing in the
standard decrees such ;->).  I can't imagine a reason for this to fail
on most PCs, but perhaps there are embedded systems that go quaint on us
here, or perhaps there are RISC machines that have these issues, or
whatever.  I'm not an expert on things behind the scenes.  All I know is
that as long as I follow the standard, and things don't work, then I have
the ability to complain to the vendor.  Otherwise, well, the vendor may
tell me it's a feature ;->

All that said, I'm not sure that the while loop version is better than the
for loop version.  ;-)

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™.