Re: [CODE] ARg these damn uilds be killin me!

From: Daniel Koepke (dkoepke@CALIFORNIA.COM)
Date: 11/25/97


> >for(i=0;guilds[i].class != -1;i++)
> >    if (GET_CLASS(ch) == guilds[i].class && world[ch->in_room].number
> >==
> >    guilds[i].guild_room) {
> >         found = TRUE;
> >         continue;
> >     }else
> >        i++;
> >
> [snip]
> >It won't recognize a person in their guild.  Any ideas?
> >
>
>    Shouldn't it be:
> for(i=0;guilds[i].class != -1;i++) {
>     if (GET_CLASS(ch) == guilds[i].class && world[ch->in_room].number >==
>     guilds[i].guild_room)
>     {
>          found = TRUE;
>          continue;
>     }
>     else
>       i++;
> }
>
> It looked like the for loop wasn't reading the incrementing of i.

An important note: spacing doesn't matter.

  if (i == 1) {

is exactly the same as

  if (i == 1)
  {

and

  } else

is exactly the same as

  }
  else

Also, a brief discussion as to what a for loop does.
The following two sections of code are functionally
equivalent (they do the same thing).

Example 1.
  int i; /* our counter */
  for (i = 0; i < 25; i++)
    printf("%d. %s\n", i, string[i])

Example 2.
  int i; /* our counter */
  i = 0; /* initialize it to a value */
  while (i < 25) { /* limit */
    printf("%d. %s\n", i, string[i]); /* example code */
    i++; /* increment at the end of the loop */
  }

The code:

  for (i = 0; guilds[i].class != -1; i++) {
    if (GET_CLASS(ch) == guilds[i].class &&
        world[ch->in_room].number == guilds[i].guild_room) {
      found = TRUE;
      continue;
    } else
      i++;
  }

Has several problems.  First, if we don't find a match we
increment twice thanks to the to second i++.  Remove the 'else'
condition entirely.  Second, we don't need to continue looking
if we already found what we were looking for.  Change the
if block code to just do 'break' instead of 'found = TRUE' and
'continue'.  We don't need 'found' because we will know if it
was found or not by the value of guilds[i].class.  So we now
have:

  for (i = 0; guilds[i].class != -1; i++)
    if (GET_CLASS(ch) == guilds[i].class &&
        world[ch->in_room].number == guilds[i].guild_room)
      break; /* end the loop, we found it */

  /* if guilds[i].class == -1, then we didn't find a match */
  if (guilds[i].class == -1) {
    .
    .
    .
    .
  }

May that give you some insight into designing your code without
using pointless variables; keeping the same functionality; and
keeping it looking nice.


daniel koepke / dkoepke@california.com


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | http://democracy.queensu.ca/~fletcher/Circle/list-faq.html |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/08/00 PST