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