开发者

Danger in using nested comments for quickly (de)activating code blocks in C++

I'm currently using nested comments to quickly activate/deactivate code during testing, the way I'm doing it is like this :

//* First Case, Activated
DoSomething();
/**/

/开发者_StackOverflow社区* Second Case, De-Activated
DoSomethingElse();
/**/

I can activate, deactivate the code blocks by simply adding or deleting a '/'.

The compiler warns me about this, as nested comments are bad, but in reality, is it dangerous to use these comments?


This is how people normally do this:

#if 0
//...
#endif

or

#define TESTWITH

#ifdef TESTWITH
//..
#endif


Yes, you will often end up overcommenting or undercommenting and having code other than you expect active and this will make debugging very confusing. Using // is much more reliable for that - you'll have to type more, but it's more predictable.


Not a direct answer, but have you considered #ifdef instead?

#define DOSOMETHING

#ifdef DOSOMETHING
DoSomething();
#else
DoSomethingElse();
#endif


Why do you feel the need to toggle code blocks on and off so often anyway? Most likely, you're doing something wrong at a higher level.

Perhaps you should be using source control, and simply create two (or more) branches, to test out different versions of your code.

Or perhaps you should refactor your code so that, instead of commenting out a whole block of code, you only need to change a single function call.

There is nothing wrong with abusing nested comments like this, but it makes your code harder to read, and it solves a problem which typically should be solved at a whole different level.


Here's how you can get into trouble:

//* First Case, Activated
DoSomething();
/**/

/* Second Case, De-Activated
/* Comment about DoSomethingElse */
DoSomethingElse();
/**/

Now, your second case will execute, because the closing of the regular comment will close your note off, and the compiler won't detect anything is amiss.

Of course, this can be averted by never using the /**/ style comments, and it depends on your environment if that's a reasonable thing to do. And a syntax-highlighting editor (even including the Stack Overflow answer editor) will tip you off to what's going on. But why introduce the possibility?

This also falls into the category of "cute." You're mixing the two different commenting syntaxes. So long as everyone understands what's going on and plays by the rules, you'll be fine. But as soon as somebody doesn't you're in trouble.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜