Sujet : Re: how to make a macro work as a single line if stmt without braces
De : bluemanedhawk (at) *nospam* invalid.invalid (Blue-Maned_Hawk)
Groupes : comp.lang.cDate : 21. Sep 2024, 22:18:07
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <pan$b0611$9f7137f3$1d714134$ee77076d@invalid.invalid>
References : 1
User-Agent : Pan/0.154 (Izium; 517acf4)
Mark Summerfield wrote:
I have this macro:
#define WARN(...) \
do { \
fprintf(stderr, "%s#%d: ", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); \
} while (0);
which I use like this:
total++;
if (failed) {
WARN("failed because...");
} else
ok++;
I would prefer to be able to write this instead:
total++;
if (failed)
WARN("failed because...");
else
ok++;
but doing so results in a compiler error:
error: 'else' without a previous 'if'
Since the initial problem has already been solved by other messages,
here's some extra completely unsolicited advice that you are free to
ignore:
If you intend for this macro to be invoked like how one would invoke the
printf function (i.e. the arguments consisting of a format string literal
followed by arguments to be formatted into it), you could get away with
defining it like this instead:
#define WARN(msg, ...) (fprintf(stderr, "%s#%d: " msg, __FILE__, __LINE__
__VA_OPT__(,) __VA_ARGS__))
This would break if you try to invoke it with a nonliteral string, because
this takes advantage of preprocessor adjacent string literal
concatenation, but modern compilers tend to complain mightily if you try
that anyway. It would have the advantage of expanding to an expression
instead, which is often more beneficial for macros because it permits more
flexibility in placement (something that i find unlikely to be relevant
for this particular one, but which can't really particularly hurt to have
anyway).
-- Blue-Maned_Hawk│shortens to Hawk│/blu.mɛin.dʰak/│he/him/his/himself/Mr.blue-maned_hawk.srht.siteHow do i run in these marrowy clogs?