How to create a "C single-line comment" macro
It doesn't work because the language specification doesn't allow it. In effect, comment removal happens before macro replacement. Once comments have been removed, //
is not a valid token (like the error message says). It can't be generated by macro replacement, and it no longer means "comment".
This is "Translation phases" in the standard. The section numbering differs, but all of C89, C99 and C11 define in phase 3:
Each comment is replaced by one space character.
and then in phase 4:
macro invocations are expanded
I used #define cout(x) //cout<<x;
for my applications. You may want to modify it like
#ifdef DEBUG
#define cout(x) cout<<x;
#else
#define cout(x)
And use it as
cout(arg0<<arg1<<arg2);
Here, you won't be commenting the line and thus won't need separate line for avoiding print. Further you can use cout wherever printing has to be done unconditionally.
cout("Print this when debugging");
cout<<"Always print this";
A debug macro:
#define DEBUG(x) x
Which can be turned off in production as:
#define DEBUG(x)
Or IIRC #undef
(sorry, my C is rusty).
Why not simply just use e.g.
#ifdef DEBUG
a = b;
#endif /* DEBUG */
Less trouble, and just as readable.