Discussion:
[m-dev.] do {} while(0) pattern in macros
Paul Bone
2018-04-26 23:46:28 UTC
Permalink
Hi Mercury team.

I remember learning the pattern:

#define PZ_WRITE_INSTR_1(code, w1, tok) \
do { \
if (opcode == (code) && width1 == (w1)) { \
token = (tok); \
goto write_opcode; \
} \
} while (0)

For macros that expand to statements while working on Mercury. While I
think that I once knew why we did this, I have now forgotten and would like
to re-learn.

Can someone remind me why we do this? My guess it's to make sure that the
macro is always a single statement and cannot be used as an expression or
expand to multiple statements in a misleading way such as in:

if (cond)
CALL_MY_MACRO(a, b);

If that's the case, why don't we just put them inside some curly brackets.

#define MAYBE_A_SAFE_MACRO(a, b, c) \
{ \
a_statement(a, b); \
another_statement(c); \
}

Thanks.
--
Paul Bone
http://paul.bone.id.au
Peter Wang
2018-04-27 00:22:19 UTC
Permalink
Post by Paul Bone
Can someone remind me why we do this? My guess it's to make sure that the
macro is always a single statement and cannot be used as an expression or
if (cond)
CALL_MY_MACRO(a, b);
If that's the case, why don't we just put them inside some curly brackets.
#define MAYBE_A_SAFE_MACRO(a, b, c) \
{ \
a_statement(a, b); \
another_statement(c); \
}
Hi Paul,

Now you've got two statements.

https://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html

Peter
Paul Bone
2018-04-27 01:35:23 UTC
Permalink
Post by Peter Wang
Post by Paul Bone
Can someone remind me why we do this? My guess it's to make sure that the
macro is always a single statement and cannot be used as an expression or
if (cond)
CALL_MY_MACRO(a, b);
If that's the case, why don't we just put them inside some curly brackets.
#define MAYBE_A_SAFE_MACRO(a, b, c) \
{ \
a_statement(a, b); \
another_statement(c); \
}
Hi Paul,
Now you've got two statements.
https://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html
Ah.

Thanks.

This seems to be a bit belt-and-suspenders (and there's nothing wrong with
that) since the Mercury style guide also says we should also always use
curlies. But I think we (Mercury) may break that rule sometimes..

Cheers.
--
Paul Bone
http://paul.bone.id.au
Loading...