Liste des Groupes | Revenir à cl c |
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).
Les messages affichés proviennent d'usenet.