xample we wish to create a cleanup macro: #define CLEAN_RETURN \ close(in_fd);close(out_fd); return; But this code doesn't work if we put it in an if statement: if (done) CLEAN_RETURN; Expanding this we get: if (done) close(in_fd);close(out_fd); return; Let's add a little whitespace for clarity: if (done) close(in_fd); close(out_fd);
The Problem: How do you create a macro that performs two statements.
For example we wish to create a cleanup macro:
#define CLEAN_RETURN \
close(in_fd);close(out_fd); return;
But this code doesn't work if we put it in an if statement:
if (done)
CLEAN_RETURN;
Expanding this we get:
if (done)
close(in_fd);close(out_fd); return;
Let's add a little whitespace for clarity:
if (done)
close(in_fd);
close(out_fd);
return;
This is not what we intended. One “solution” is to enclose the statements
in {}.
#define CLEAN_RETURN \
{ close(in_fd);close(out_fd); return; }
Now our if statement expands to:
if (done)
{ close(in_fd);close(out_fd); return; };
This works. Sort of. The problem is if we try an if / else statement:
if (done)
CLEAN_RETURN;
else
not_done_yet();
This gives us a syntax error when we try and compile it. Why?
Let's look at the expanded code:
if (done)
{ close(in_fd);close(out_fd); return; };
else
not_done_yet();
There's an extra semicolon on the line. This didn't bother us when there
was no else, but now that there is one, the compiler gets confused.
So how do we define a multi-statement macro that can be used like a
statement?
Step by step
Solved in 3 steps