Re: Problems with arg manipulation

From: Daniel A. Koepke (
Date: 06/15/02

On Sun, 16 Jun 2002, Alex Mann wrote:

> if (arg == "str") ******This picks out the train str ********

No, this compares the address of the first character in arg to the address
of the static string "str".  Your problem is a frequent one with beginning
C programmers, as C is a lower-level language than what people at first
expect.  A useful generalization to help you understand and remember the
issue at hand: C doesn't define built-in operations on composites types,
such as arrays or structures.  If you think you've found one, chances are
you're misunderstanding what's going on.

So what do we do now?  In general, we must work with the pieces that make
up a composite.  In this case, we must work on each character of the
string individually.  We can compare characters because they're a
non-composite (simple) type.  This is needed enough in C that the C
library includes a function for doing it: strcmp().

That's not quite it.  First, we have to worry about case sensitivity.
strcmp() respects the case you give it, so "str" will not match "STR".
To get around this, use CircleMUD's str_cmp() function.  (Note that you
should use str_cmp() even if your platform has a case insensitive version
of strcmp() available already; on these platforms, str_cmp() is just an
alias for the platform-specific function.)

Second, take note of what str_cmp() (and strcmp()) return.  The short
description is that they return zero (0) on *success*.  If you're
interested in why this is so, feel free to send me a private e-mail and
ask (or read 'man strcmp' if on a UNIX system).

So we've come to our answer, and it's just as short as the original

    if (!str_cmp(arg, "str"))  /* If arg matches "str". */

Some people find reading this weird because of the ! (not) -- it looks
like you're checking if arg is NOT equal to "str".  Those people often

    if (str_cmp(arg, "str") == 0)

instead.  They are exactly equivalent, but most people prefer the shorter
version because programmer's are notoriously lazy typists.


   | FAQ: |
   | Archives: |
   | Newbie List:   |

This archive was generated by hypermail 2b30 : 06/25/03 PDT