Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 21 May 2001 15:26:30 -0700 (PDT)
From:      John Wilson <john_wilson100@excite.com>
To:        freebsd-questions@freebsd.org
Subject:   Question for C preprocessor gurus
Message-ID:  <11895256.990483991242.JavaMail.imail@zero.excite.com>

next in thread | raw e-mail | index | archive | help
In this program I'm writing, I need to define a simple list of errors, e.g.

#define ERR_OK     0
#define ERR_BAD    1
#define ERR_AWFUL  2

and a function to return error descriptions:

char *f(int error_no)
{
  switch (error_no)
  {
  case ERR_OK:
     return "OK";

  case ERR_BAD:
     return "Bad";

  /* .... */
  }
}


There is nothing wrong with this code, except one thing - to add a new
error, I need to do it in two different places.   I was therefore wondering
if it was possible to avoid adding the same strings twice through (ab)use of
the preprocessor.

Of course, I could do something like this:

static char *Errors[] = {
"ERR_OK",
"ERR_BAD",
"ERR_TERRIBLE"
}

and then define

char* ErrorDescription(int error_code)
{
  if ((error_code >= 0) &&
      (error_code < sizeof(Errors)/sizeof(Errors[0])))

      return Errors[error_code];
  else
      return "UNDEFINED ERROR";
}

but then I wouldn't be able to refer to the errors by name.

Ideally, I would like to say

DEFINE_ERROR(ERR_OK, 0)
DEFINE_ERROR(ERR_BAD,1)

and have the preprocessor generate something like this:

static char *Errors[] = {

#define ERR_OK 0
	"ERR_OK",
#define ERR_BAD 1
	"ERR_BAD"
}


Any ideas?

Thanks

John Wilson





_______________________________________________________
Send a cool gift with your E-Card
http://www.bluemountain.com/giftcenter/



To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?11895256.990483991242.JavaMail.imail>