J
James Kanze
James Kanze wrote:
[...]
Another advantage of using a macro is that I can (and do)
conditionally compile it, so that I can completely remove the
Trace code (although I can also control it programmatically).
Conditional compilation should also be used sparingly, and
this is the only place I use it in what has now become a
substantial sized project.
I've provided for this possibility many times as well. I've
never had to use it, but often, it's a necessary argument to
sell tracing.
Another place I use macros is to replace curly brackets. Eg
// Global include
#define THEN {
#define ELSEIF }else if
#define ELSE }else{
#define ENDIF }
// -----------------
Then I can write
if (condition)
THEN
// Do something
ELSE
// Do something else
ENDIF
This may be controversial,
It's not controversial; it's proven bad practice. You've just
made your code unreadable by any other C++ programmer, and by
any other tool which doesn't to a full parse (syntax
highlighting and indenting by the editor, for example).
C++ has a defined syntax. I don't always like it either, but
that's the way it is. You can't really create a new language
with macros, and you don't really want to, since no one else
(and no tool) knows that language. For better or for worse, you
have to live with C++ as it is.
(Also, if you were doing it, the #defines would be:
#define IF if (
#define THEN ) {
#define ELSE } else {
#define ELSIF } else if (
#define END }
..)
but I think it makes code clearer. My code automatically
documents where the various parts of the if statement are,
rather than leaving the reader to count brackets and look at
indentation.
How is counting the brackets and looking at the indentation any
better than counting the THEN/ELSE and looking at the
indentation. My editor does the indentation automatically (as
do most, I think), which ensures that it is correct, and it's
doubtlessly the easiest thing to follow. (And of course, I
don't nest overly deep, so there's not that much to follow
anyway.)