It appears in not just one language that comments can't be nested. Do you have a good solution for this problem? One workaround in C/C++ and Java is to only use the single-line comment but it becomes impossible then to comment out a larger block. I'm facing something like this:
</li><!--
<li><!-- Save -->
So I must manually go through and edit the comments. Can you advice how we should handle this, in many languages? I'm not sure but maybe python has a solution for this with the '''
way that might be able to include a #
comment in python?
`
Best Answer
The best solution is, obviously, to just not nest your comments. Nested comments are usually a sign that you are using comments wrong. The most common example is commented-out code that contains comments itself, and the fix is to remove the code instead of commenting it out.
That said, many programming languages have more than one type of comment syntax, and you can use this fact to nest at least one level deep. For example, in Java:
Also, in many languages, at least one type of comment is kind-of-nestable; in C-like languages, line comments inside line comments are ignored:
Most IDEs support commenting entire blocks of code with line comments in one action, and they handle this kind of commenting style correctly. The same example in Python:
Often, coding standards for a particular project have rules about which comment style to use when; a common convention is to use block comments (
/* */
) for method and class documentation, and inline comments (//
) for remarks inside method bodies and such, e.g.:With such a style, it is unlikely that you'll ever need to nest
/* */
comments (if you have to temporarily disable entire methods or classes, renaming them work just as nicely, if not better); and//
comments do nest, at least with a little help from your IDE.Finally, to disable code, you have other options in many programming languages; for example, in C, you can leverage the preprocessor:
In dynamic languages, you can often just use regular
if
statements instead:However, unlike the CPP example, this strategy requires the source file as a whole to be syntactically valid, so it's by far not as flexible.
And finally, there are at least some languages that allow for nested comments. In case you're interested, wikipedia has a nice comparison chart.