TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Neil Heller
from: Darin McBride
date: 2004-04-19 18:01:02
subject: Squares

Hello Neil!

Replying to a message of Neil Heller 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.

 DM>> Good catch!

 NH> How so?  These sure _look_ like they do the same thing.

And thus we see exactly how trying to be clever to gain optimisations can
shoot you in the foot - someone said I was one of the gurus here (which I
deny, but that's another story), and even I missed it until someone else
pointed it out to me.

The while statement will always increment s such that it points to the
character after the nul, which means it's pointing to space that's either
unallocated (the one byte after allocated memory is allowed to be pointed
at, but not dereferenced, unlike the byte before allocated memory), or at
least garbage.

The for loop only increments s until it points to a nul, such that after
the for-loop is over, s is pointing at the nul.

Subtle, but can bite you if you try to use s afterwards and you don't
recognise which one points where.

It's all just crazy.  Loopy, I tell ya!

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