Article View: comp.lang.c.moderated
Article #2376Re: Macros and Braces
From: Kurt Watzka
Date: Sun, 24 Mar 1996 17:48
Date: Sun, 24 Mar 1996 17:48
53 lines
1940 bytes
1940 bytes
100576.1776@compuserve.com (Antony Pace (UK/CH)) writes:
>Hi all,
>I am having problems writing a macro (Ansi C) for which I feel there
>must be standard technique. Can anyone help?
[some text edited]
>#define CLEAR_ERROR(e) { \
> (e).a = 0; \
> (e).b = 0; \
> (e).c = 0; \
> TRACE("clear error"); \
>}
[example of a situation where "CLEAR_ERROR(foo);" works edited]
>Note how the semicolon I put after the invocation becomes a null
>statement. I expect users of my CLEAR_ERROR macro to use it, as then
>the macro looks like a function call.
>In this code segment, my macro does not work:
> ...
> if (a==3)
> CLEAR_ERROR(error);
> else
> b=5;
> ...
This is why "function like" macros should not be defined using "raw"
braces. A useful solution is to put the "body" of the macro in a
"do { ... } while(0)" loop.
#define CLEAR_ERROR(e) do { \
(e).a = 0; \
(e).b = 0; \
(e).c = 0; \
TRACE("clear error"); \
} while (0)
Now you _need_ a semicolon after the "invocation" of the macro. I would
not dare to claim that this is a "standard technique", but the only
potential problem I see is that you have to persuade lint that you
_really_ want a constant conditional expression in that while statement.
Kurt
--
| Kurt Watzka Phone : +49-89-2180-6254
| watzka@stat.uni-muenchen.de
| ua302aa@sunmail.lrz-muenchen.de
Technical Details
Message-ID:
<4j41t7$ns1@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4j06iu$7qm@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: watzka@stat.uni-muenchen.de (Kurt Watzka) Newsgroups: comp.lang.c.moderated Subject: Re: Macros and Braces Date: 24 Mar 1996 11:48:23 -0600 Organization: Leibniz-Rechenzentrum, Muenchen (Germany) Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4j41t7$ns1@solutions.solon.com> References: <4j06iu$7qm@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com