use of do{...}while(0)

G

Giorgos Keramidas

I have got zero marks in both of the exercises!?

Do the expansion of DO_MAGIC_STUFF(quux) in your head, or use a
preprocessor on the source posted by Joona I Palaste. Then the question
is transformed to:

- Why does the following fail to compile?

if (willDoMagic)
{foo(x); bar(x);};
else
printf("Won't do magic stuff!\n");

Hint: pay very close attention to semicolons.

There are also a few problems with macros that use do{ ... } while (0)
_and_ are expected to work "exactly" like functions (i.e. return a
meaningful value), as Lawrence Kirby has noted.

AFAIK, there is no way to guarantee that a compound statement has a
value. Thus, you cannot "return" the value of set_foo() in code like
this:

int set_foo(int *p, int val)
{
if (p == NULL)
return (-1);
*p = val;
return (0);
}

#ifdef DEBUGGING
#define SETFOO(p,x) do {
int retval;
retval = set_foo((p), (x));
if (retval == -1)
fprintf(stderr, "set_foo: Oops!\n");
} while (0)
#else
#define SETFOO(p,x) set_foo((p), (x))
#endif

The best way I know, until now, to actually _return_ a value is by using
a real function as a wrapper:

int set_foo(int *p, int val)
{
if (p == NULL)
return (-1);
*p = val;
return (0);
}

#ifdef DEBUGGING
#define SETFOO(p,x) my_set_foo((p), (x))

int my_set_foo(int *px, int x)
{
int retval;

retval = set_foo(px, x);
if (retval == -1)
fprintf(stderr, "set_foo: Oops!\n");
return (retval);
}
#else /* !DEBUGGING */
#define SETFOO(p,x) set_foo((p), (x))
#endif /* DEBUGGING */

Note, though, that this uses an extra function call, so in many cases
the overhead may not be acceptable.

- Giorgos
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,414
Latest member
GayleWedel

Latest Threads

Top