Search code examples
c++coding-stylecomments

Is it a bad practice to use C-style comments in C++ code?


While reading this wikipedia article about , I came across this statement:

Many programmers avoid using C-style comments and instead use C++ style single line comments.

Is this correct? If so, why is that? Is it just a habit or there are some technical and rational reasons behind this?


Examples from aforementioned article:

/**
 * <A short one line description>
 *
 * <Longer description>
 * <May span multiple lines or paragraphs as needed>
 *
 * @param  Description of method's or function's input parameter
 * @param  ...
 * @return Description of the return value
 */

vs.

/// <A short one line description>
///
/// <Longer description>
/// <May span multiple lines or paragraphs as needed>
///
/// @param  Description of method's or function's input parameter
/// @param  ...
/// @return Description of the return value

Solution

  • The C-style comments /* */ cannot be nested recursively. Stacking multiple single line comments on each other, like this '//////', is not a problem. This way you can comment out a part of the code incrementally. Visual Studio for example supports this with functionality to increase/decrease the number of comment levels in this fashion.

    A reason in favour of '/* */'-style comments is to make special types of comments stand out when scrolling through the code, such as method documentation. This creates a nice visual structure to the code as well.

    Another use-case of '/* */' comments are the sort of inline comments which have code to both sides, such as void myfunc(double size /* = 0 */) { ... } to make a default value visible in the cpp file.

    A possible approach to combine both benefits is:

    • use '//' inside methods (where you want to comment in/out out repeatedly) and
    • use '/* */' only for special types of comments like doxygen documentation in the cpp for example.