Can C++ Style comments replace C-Style comments?

5 04 2008


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.

Advertisements