Sujet : Re: how to make a macro work as a single line if stmt without braces
De : bc (at) *nospam* freeuk.com (Bart)
Groupes : comp.lang.cDate : 21. Sep 2024, 11:13:00
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vcm2mr$1humj$1@dont-email.me>
References : 1
User-Agent : Mozilla Thunderbird
On 21/09/2024 08:35, 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'
Remove the semicolon at the end of the macro.
As it is, it compiles to:
if (failed) do {...} while 0;; else ok++:
There are two semicolons together, the second terminates the whole if statement, leaving an open 'else'.