Can C++ Style comments replace C-Style comments?
![]()
While entering to C++ world, the first thing we used to learn is – Avoid C-Style comments, always use C++ style comments and a number of drawbacks of C-Style comments. But don’t think that C++ comments are omni. Still there are places where C++ style comments cannot be used.
![]()
Usually inside macros, we don’t write comments. But if the macro is too complex, adding comments will be better for future. But can we use C++ style comments? See the following code block.
#define CHECK_AND_DELETE_PTR( ptr ) \
// Check whether the pointer is valid \
if( ptr ) \
{ \
// Delete the pointer \
delete ptr; \
}
The code block won’t compile. Because C++ style comments always look for end-of-line as termination and the backslash delimiter that we add will concatenate the next line and that too will become the part of comment. Since macro body should be in a single line, we cannot omit the backslash delimiter.
See the same macro with C-Style comments which is perfect.
#define CHECK_AND_DELETE_PTR( ptr ) \
/* Check whether the pointer is valid */ \
if( ptr ) \
{ \
/* Delete the pointer */ \
delete ptr; \
}
Immortal C. Isn’t it?
![]()
Targeted Audience – Intermediate.
I am little bit confused that C++ is discouraging the old C style comments. Ofcourse C style comment has some problems, but I think that C++ has only introduced a simple single line comment in the form of “//” rather than a “/* …. */”.
Am I right?
I think that // is not just a replacement for /* */ in order to remove the ending */. CStyle comments have more potential issues such as nested comments which often bite us. Refer Effective C++ for detailed description about why // is recommenced to use.
Best C++ coding practices( as I said, Effective C++ ) which floats around us do discourage using CStyle comments. Because they have some drawbacks. Thats why C++ introduced new commenting style. Reading those, an average guy feels that C++ style comment is the best because its more safer. But, this article just points out that everything does have an Achilles heel.