[ILUG] C puzzle

Paul Jakma paul at clubi.ie
Thu Jul 1 16:00:43 IST 2004


slightly OT i know...

Anyone have a suggestion as to how to achieve something akin to:

list list;
listmember this;
listmember next;

for (this = list->head;
      ((this != NULL) ? next = this->next : next = this);
      this = next)

Which is not (strictly) allowed.

Essentially, I have a body of code that uses a macro defined as:

#define LIST_LOOP(L,V,N) \
   for ((N) = (L)->head; (N); (N) = (N)->next)
    if (((V) = (N)->data) != NULL)

which allows usage such as:

   LIST_LOOP (list, val, this)
      <statement>;

and

   LIST_LOOP (list, val, this)
     {
       <statements>;
       ...
     }

However, every now and then bugs are discovered[1] due to usage such 
as:

   LIST_LOOP (list, val, this)
     {
       ....
       delete_member (this);
       ....
     }

Now, before I go and kill this macro altogether (precisely for 
obfuscating things sufficiently to make bugs like above more likely), 
I was wondering if there was any cute way to make this macro immune 
to this bug by taking its reference to the next list element before 
each iteration. However, I can't find any way to do it, at least not 
portably (gcc will allow conditional lvalues, but warns that they are 
deprecated - didnt test to see if it actually worked though, 
non-portable isn't worth much). I'm really curious as to whether 
there is a way or not.

1. Recent FreeBSD is rather good at it, their libc poisons freed 
memory, quite cute.

regards,
-- 
Paul Jakma	paul at clubi.ie	paul at jakma.org	Key ID: 64A2FF6A
 	warning: do not ever send email to spam at dishone.st
Fortune:
Each new user of a new system uncovers a new class of bugs.
 		-- Kernighan



More information about the ILUG mailing list