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?
![](/static/compass_v2/shared-icons/check-mark.png)
Step by step
Solved in 3 steps
![Blurred answer](/static/compass_v2/solution-images/blurred-answer.jpg)
![Computer Networking: A Top-Down Approach (7th Edi…](https://www.bartleby.com/isbn_cover_images/9780133594140/9780133594140_smallCoverImage.gif)
![Computer Organization and Design MIPS Edition, Fi…](https://www.bartleby.com/isbn_cover_images/9780124077263/9780124077263_smallCoverImage.gif)
![Network+ Guide to Networks (MindTap Course List)](https://www.bartleby.com/isbn_cover_images/9781337569330/9781337569330_smallCoverImage.gif)
![Computer Networking: A Top-Down Approach (7th Edi…](https://www.bartleby.com/isbn_cover_images/9780133594140/9780133594140_smallCoverImage.gif)
![Computer Organization and Design MIPS Edition, Fi…](https://www.bartleby.com/isbn_cover_images/9780124077263/9780124077263_smallCoverImage.gif)
![Network+ Guide to Networks (MindTap Course List)](https://www.bartleby.com/isbn_cover_images/9781337569330/9781337569330_smallCoverImage.gif)
![Concepts of Database Management](https://www.bartleby.com/isbn_cover_images/9781337093422/9781337093422_smallCoverImage.gif)
![Prelude to Programming](https://www.bartleby.com/isbn_cover_images/9780133750423/9780133750423_smallCoverImage.jpg)
![Sc Business Data Communications and Networking, T…](https://www.bartleby.com/isbn_cover_images/9781119368830/9781119368830_smallCoverImage.gif)