Conceptcore
Comment
Also called comment, comments, code comment, source code comment, line comment, block comment, doc comment, documentation comment, docstring, remark, commenting out.
A comment is text in source code that the compiler or interpreter ignores. It holds notes for human readers, and tools can read some comments as documentation or as directives.
- Applies to
- core-languages
Idea
A comment is a part of the source text that is for people and not for the machine. The lexer finds each comment and drops it, so the program means the same with or without it. To find a comment, the lexer must know where strings start and end, because a comment marker inside a string literal is plain text.
import io
import re
import tokenize
src = '''x = 1 # set x
url = "http://example.com/#top" # the # in the string is not a comment
y = x + 1
'''
# A naive rule cuts at the first #, which breaks the string.
naive = [line.split("#")[0].rstrip() for line in src.splitlines()]
print("naive:", naive[1])
# A lexer knows where strings start and end, so it finds only the real comments.
for tok in tokenize.generate_tokens(io.StringIO(src).readline):
if tok.type == tokenize.COMMENT:
print(f"line {tok.start[0]} col {tok.start[1]:>2}: {tok.string}")
# After the lexer drops comments, the program is the same token stream.
def code_tokens(s):
return [t.string for t in tokenize.generate_tokens(io.StringIO(s).readline)
if t.type not in (tokenize.COMMENT, tokenize.NL, tokenize.NEWLINE, tokenize.ENDMARKER)]
print(code_tokens("y = x + 1 # add one\n") == code_tokens("y = x + 1\n"))
naive: url = "http://example.com/
line 1 col 7: # set x
line 2 col 33: # the # in the string is not a comment
True
The naive rule cuts each line at the first #, so it breaks the URL in the string. The tokenizer reports only the two real comments, with their line and column. The last line shows that a comment does not change the program: the code tokens of the two lines are the same.
How it works
Line and block comments. A line comment starts with a marker and ends at the end of the line: # in Python, Bash and many scripting languages, // in the C family, -- in SQL. A block comment has a start marker and an end marker, such as /* */, and can cover part of a line or many lines. Python has only the line form. In Python, "A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line", and "Comments are ignored by the syntax"1.
The lexer removes them. Comments are not tokens. The lexer reads them and drops them, or turns them into whitespace, so the parser never sees them. The Rust reference says that "Non-doc comments are interpreted as a form of whitespace"2. In C, "All comments are removed from the program at translation phase 3 by replacing each comment with a single whitespace character"3, so int/**/x is int x and not intx. Because comments go before the preprocessor runs, "a macro cannot be used to form a comment"3.
Order of the lexical steps. A language can change the source text before it looks for comments, and this can surprise a reader. In C, a backslash at the end of a line joins the next line to it in phase 2, so a // comment that ends with a backslash also hides the next line3. In Java, the compiler translates Unicode escapes such as \u000a before it finds comments, so an escape for a line break ends a line comment, and the text after it is code4.
Nesting. In C, C++, Java and JavaScript, block comments do not nest: the first */ ends the comment435. The Java specification states that "Comments do not nest"4. So a programmer cannot comment out a block of code that already holds a block comment. Rust is different: "Nested block comments are supported"2.
Comments that tools read. Some comments have meaning for a tool, but not for the compiler:
- A doc comment documents the declaration after it. Javadoc reads
/** */in Java, and in C# the compiler "finds all comment fields with XML tags in the source code and creates an XML documentation file from those comments"6. In Go, a doc comment is a comment that appears "immediately before top-level package, const, func, type, and var declarations with no intervening newlines"7. - In Rust,
///and//!doc comments are attributes:/// Foo"turns into#[doc=" Foo"]"2. - A directive is a comment that tells a tool what to do. In Go, "Directive comments such as //go:generate are not considered part of a doc comment and are omitted from rendered documentation"7. In Python, a comment in the first or second line can declare the encoding of the file1. In JavaScript, a hashbang comment
#!is valid only at the start of a script or module8.
Docstrings are not comments. A Python docstring "is a string literal that occurs as the first statement in a module, function, class, or method definition", and it "becomes the __doc__ special attribute of that object"9. It stays in the program at run time, and a comment does not.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the comments of JavaScript, and a triple-slash directive such as /// <reference path="..." /> is a comment that the compiler reads, but no example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has // and /* */ comments, its block comments nest, and KDoc reads /** */ comments, but no example file exists because kotlinc is not installed. |
| SQL | Native | Standard SQL has -- line comments, and most databases also accept /* */ block comments. No example file exists. |
| Bash | Native | A word that starts with. |
| PowerShell | Native | PowerShell has. |
| HTML | Native | An HTML comment starts with <!-- and ends with -->, and the browser keeps it in the DOM as a comment node. |
| CSS | Native | CSS has only /* */ block comments, and they do not nest; // is not a comment in CSS. |
| Regular expressions | Native | Python, PCRE and Perl accept the comment group (?#...) and a verbose mode in which # starts a comment, but JavaScript has neither. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | # line comments; docstrings are string literals |
| JavaScript | native | //, /* */; #! at the start of a script |
| TypeScript | native | as JavaScript; /// <reference> directives |
| Java | native | //, /* */; Javadoc /** */ |
| Kotlin | native | //, /* */ that nest; KDoc /** */ |
| C# | native | //, /* */; XML doc comments /// |
| Go | native | //, /* */; doc comments; //go: directives |
| Rust | native | //, /* */ that nest; /// and //! doc comments |
| C | native | /* */; C99 // |
| C++ | native | //, /* */ |
| Bash | native | # at the start of a word |
| PowerShell | native | #, <# #>; comment-based help |
| SQL | native | --, /* */ |
| Regex | native | (?#...) and verbose mode in many engines; not in JavaScript |
| HTML | native | <!-- --> |
| CSS | native | /* */ only |
Every language in the table has comments, so the verdict is native. The languages differ in three things: whether block comments nest, which comments tools read as documentation, and how the other lexical steps interact with comments.
The example files show these differences. Python compares a docstring with a comment and shows that the compiled code keeps only the docstring. JavaScript shows that block comments do not nest, that a block comment with a line break ends a return statement, and that JSON.parse does not accept comments. Java shows a Unicode escape that ends a line comment. C# reads an attribute by reflection, because reflection cannot see comments. Go reads doc comments and a directive with go/parser. Rust shows nested comments and doc attributes. C shows a line splice, the one space that replaces a comment, and the //* sequence that C89 and C99 read differently. C++ shows a raw string, #if 0 and a macro that cannot make a comment.
import inspect
# Return the area of a circle.
def area(r):
"""Return the area of a circle of radius r.
A docstring is a string literal, so it stays in the program at run time.
"""
return 3.14159 * r * r # pi to 5 decimal places
print(area.__doc__.splitlines()[0])
print(repr(inspect.getcomments(area)))
# A comment is gone after parsing; the compiled code has no trace of it.
print("pi to 5" in str(area.__code__.co_consts))
# A string as the first statement is a docstring and is kept.
# A string on its own line later is an expression statement, and the compiler drops it.
for text in ['"first"\nx = 1\n', 'x = 1\n"later"\n']:
code = compile(text, "<demo>", "exec")
print([c for c in code.co_consts if isinstance(c, str)])
Return the area of a circle of radius r.
'# Return the area of a circle.\n'
False
['first']
[]
- Verdict: native.
#starts a comment that ends at the end of the line, and Python has no block comment.inspect.getcommentsreads the comment lines above a function from its source file. A docstring is a string literal, so__doc__keeps it at run time, but the compiled code has no trace of the comment. A string statement that is not the first statement is not a docstring, and the compiler drops it.
#include <iostream>
#include <string>
int main() {
// A raw string keeps the comment markers as text.
std::string s = R"(/* not a comment */ // nor this)";
std::cout << s << "\n";
#if 0
This block is not compiled. It can hold code that does not parse,
and it can hold /* a block comment */ without a nesting problem.
#endif
// The preprocessor removes comments before it expands macros,
// so a macro body cannot make a comment.
#define SLASH /
#define STR(x) #x
#define XSTR(x) STR(x)
std::cout << XSTR(SLASH SLASH x) << "\n"; // two / tokens, not a comment
/** A Doxygen comment is a normal comment to the compiler. */
std::cout << "done\n";
}
/* not a comment */ // nor this
/ / x
done
- Verdict: native. C++ has the comments of C. A raw string keeps comment markers as text.
#if 0removes a block that can contain block comments. Comments are removed before macro expansion, so the macroSLASHgives the token/, and two of them stay two tokens, as/ / xshows. Doxygen reads/** */comments, but to the compiler they are normal comments.
public class Main {
/**
* Returns the larger of two ints. Javadoc reads comments that start with two stars.
*/
static int max(int a, int b) {
return a > b ? a : b;
}
public static void main(String[] args) {
System.out.println(max(3, 7));
// The compiler turns unicode escapes into characters before it finds comments,
// so the escape for a line break ends this comment: \u000a System.out.println("This line runs.");
/* Block comments do not nest, so a star-slash inside one ends it early. */
String s = "/* inside a string, this is not a comment */";
System.out.println(s.length());
}
}
7
This line runs.
44
- Verdict: native. Java has
//,/* */and the Javadoc form/** */. The compiler translates Unicode escapes before it finds comments, so\u000ain a line comment is a real line break, and the statement after it runs. Comment markers inside a string literal are text, so the string has 44 characters.
#include <stdio.h>
int main(void) {
int n = 1;
// A backslash at the end of a line comment joins the next line to it: \
n = n + 1;
printf("n = %d\n", n);
int/**/x = 5; /* the compiler replaces a comment with one space */
printf("x = %d\n", x);
/* Block comments do not nest in C. The first end marker closes this comment: /* inner */
printf("%s\n", "/* in a string, this is text */");
int a = 8, b = 2;
printf("%d\n", a //* a line comment starts here in C99, so this is a / b in C89 */ b
+ 0);
(void)b;
return 0;
}
n = 1
x = 5
/* in a string, this is text */
8
- Verdict: native. C has
/* */and, since C99,//. Comments are removed in translation phase 3, and each one becomes one space, soint/**/xdeclaresx. A backslash at the end of a//line joins the next line to the comment, son = n + 1;does not run, and clang warns with-Wcomment. Block comments do not nest. In C89,a //* ... */ bmeanta / b, but since C99//starts a comment, so the program prints8.
using System.Reflection;
Console.WriteLine(Geometry.Area(2));
// Comments are gone after compilation; reflection sees attributes, not comments.
var m = typeof(Geometry).GetMethod("Area")!;
Console.WriteLine(m.GetCustomAttribute<System.ComponentModel.DescriptionAttribute>()?.Description);
// Text that looks like a comment inside a string is part of the string.
Console.WriteLine("// not a comment".Length);
// #if false removes a region that may itself contain block comments, which /* */ cannot do.
#if false
/* first */ Console.WriteLine("removed"); /* second */
#endif
Console.WriteLine("done");
static class Geometry
{
/// <summary>Returns the area of a circle.</summary>
/// <param name="r">The radius.</param>
[System.ComponentModel.Description("area of a circle")]
public static double Area(double r) => Math.PI * r * r; // the compiler ignores this
}
12.566370614359172
area of a circle
16
done
- Verdict: native. C# has
//and/* */, and a///comment holds XML that the compiler writes to a documentation file whenGenerateDocumentationFileis set. Reflection cannot read comments, so a program that needs the text at run time uses an attribute such asDescription.#if falseremoves a region that holds block comments.
// A function's source text keeps its comments, so toString shows them.
function add(a, b) {
/* the sum */ return a + b; // done
}
console.log(add.toString().split("\n")[1].trim());
// Block comments do not nest: the first */ ends the comment.
for (const src of ["/* a /* b */ 1", "/* a /* b */ c */ 1"]) {
try {
console.log(JSON.stringify(src), "=>", new Function(`return ${src}`)());
} catch (e) {
console.log(JSON.stringify(src), "=>", e.name);
}
}
// A comment that contains a line break acts as a line break for automatic semicolon insertion.
const f = new Function("return /*\n*/ 42");
console.log(f());
// JSON has no comments.
try {
JSON.parse('{"a": 1 /* no */}');
} catch (e) {
console.log("JSON:", e.name);
}
/* the sum */ return a + b; // done
"/* a /* b */ 1" => 1
"/* a /* b */ c */ 1" => SyntaxError
undefined
JSON: SyntaxError
- Verdict: native.
//and/* */are the two usual comment forms, and a hashbang line#!at the start of a script is a third form.Function.prototype.toStringreturns the source text, so it keeps the comments. Block comments do not nest, so the second string is a syntax error. A block comment that contains a line break ends thereturnstatement, so the function returnsundefined.JSON.parserejects comments.
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"strings"
)
const src = `package geo
// Area returns the area of a circle of radius r.
// A doc comment is the comment right before a declaration.
func Area(r float64) float64 {
return 3.14159 * r * r // pi to 5 places
}
//go:noinline
func helper() {}
`
func main() {
fset := token.NewFileSet()
// Without parser.ParseComments, the parser drops all comments.
f, err := parser.ParseFile(fset, "geo.go", src, parser.ParseComments)
if err != nil {
panic(err)
}
for _, d := range f.Decls {
fn := d.(*ast.FuncDecl)
fmt.Printf("%s: %q\n", fn.Name.Name, strings.TrimSpace(fn.Doc.Text()))
}
// Doc.Text drops directives such as //go:noinline, but they are still in the comment list.
fmt.Println(len(f.Comments), "comment groups;", f.Comments[2].List[0].Text)
}
Area: "Area returns the area of a circle of radius r.\nA doc comment is the comment right before a declaration."
helper: ""
3 comment groups; //go:noinline
- Verdict: native. Go has
//and/* */comments. A doc comment is the comment right before a top-level declaration, andgo/parserkeeps comments only with theParseCommentsflag.Doc.Textleaves out a directive such as//go:noinline, but the directive is still in the comment list of the file, and the toolchain reads it there.
//! An inner doc comment documents the item that contains it, here the crate.
/// Returns the area of a circle.
/// An outer doc comment is the same as the attribute #[doc = "..."].
fn area(r: f64) -> f64 {
std::f64::consts::PI * r * r
}
#[doc = "Returns twice x. This attribute is a doc comment written in the long form."]
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
println!("{:.4} {}", area(1.0), double(21));
/* Block comments nest in Rust:
/* this inner comment */
and this line is still inside the outer one. */
println!("after a nested comment");
// Comments are not tokens, so a macro never sees them.
println!("{}", stringify!(a /* hidden */ + b // also hidden
));
// In a string, the comment markers are plain text.
println!("{}", r"// not a comment /* nor this */".len());
}
3.1416 42
after a nested comment
a + b
31
- Verdict: native. Rust block comments nest, so a region that is commented out can hold other block comments.
///and//!are doc comments, the same as a#[doc]attribute, and rustdoc reads them. Other comments are whitespace, sostringify!seesa + bwith no comment text.
Variations and related ideas
- Commenting out code. A programmer often turns code into a comment to stop it from running. Line comments are safer for this than block comments, because block comments do not nest in most languages. In C and C++,
#if 0and#endifremove a block that holds comments5. - Doc comments and doc generators. Javadoc, the C# XML documentation, Go doc comments, rustdoc and Doxygen turn comments into reference documentation. See annotations for metadata that the compiler keeps.
- Docstrings. Python, Lisp dialects and Julia keep documentation as a string value at run time, so a program can read it, for example with
help. - Pragmas and directives.
//go:lines,# type: ignorefor Python type checkers,// eslint-disableand#!lines are comments to the language but instructions to a tool. See syntactic macros for other text that tools change before compilation. - Comments in data formats. JSON has no comments. YAML and TOML use
#, and XML and HTML use<!-- -->.
Pitfalls
- Comments that do not match the code. The compiler does not check comments, so a comment can stay after the code changes. A wrong comment is worse than no comment. Explain why the code does something, and let the code show what it does.
- Commented-out block comments.
/* ... */around code that holds*/ends early, and the rest is code again. Use line comments,#if 0in C, or delete the code and use version control. - A backslash at the end of a C line comment. It joins the next line to the comment, so the next statement is lost. Clang and GCC warn with
-Wcomment. - Unicode escapes in Java comments.
\u000aends a line comment, and the escapes for*and/end a block comment, because the compiler translates them first. - Comment markers in strings and regular expressions. A tool that strips comments with a simple pattern breaks strings such as
"http://". Use the tokenizer of the language, as the idea example does. - Block comments and automatic semicolon insertion. In JavaScript, a block comment that contains a line break acts as a line break for automatic semicolon insertion8, so
return /* ... */across lines returnsundefined. - Comments in shipped code. Comments in JavaScript, CSS and HTML go to the browser unless a minifier removes them. Do not put secrets or internal notes in them.
Cost
A compiled program has no cost from comments at run time, because the compiler removes them. The lexer still reads each comment, so very large comments make the build a little slower. In an interpreted language, the interpreter also drops comments when it reads the source. Docstrings are different, because they are values: Python keeps them in memory, and the option -OO removes them. In code that goes over the network, such as JavaScript for a web page, comments add bytes until a minifier removes them.
History
The 1956 FORTRAN manual for the IBM 704 says that "Punching the character C in column 1 will cause the card to be ignored by FORTRAN. Such cards may therefore be used to carry comments which will appear when the deck is listed"10. Fixed-form Fortran kept this rule, and Fortran 77 also allowed an asterisk in column 111.
The two comment forms of the C family have different sources. C had only /* */. Bjarne Stroustrup wrote that, of the languages he considered, BCPL "gave // comments" to C++ as released in 1985, and that "Since both styles of comments are allowed people can simply use the style they like best"12. C added // in C993. Later languages such as Java, C#, JavaScript, Go and Rust kept both forms. Java, C# and Go added doc comments, Python added docstrings, and Rust made doc comments attributes94672.
References
- Lexical analysis, The Python Language Reference, 2.1.3 Comments; 2.1.4 Encoding declarations
- Comments, The Rust Reference, Lexer; Doc comments
- Comments, C reference, cppreference.com, Explanation; Notes
- The Java Language Specification, Java SE 25 Edition, Chapter 3, 3.3 Unicode Escapes; 3.7 Comments
- Comments, C++ reference, cppreference.com, C-style; Notes
- Documentation comments, C# language reference, Introduction
- Go Doc Comments, Introduction; Directives
- Lexical grammar, MDN Web Docs, Comments
- PEP 257, Docstring Conventions, What is a Docstring?
- The FORTRAN Automatic Coding System for the IBM 704 EDPM, Programmer's Reference Manual, IBM, 1956, Chapter 1, Keypunching the Program
- Comment (computer programming), Wikipedia, Fortran
- A History of C++, 1979 to 1991, Bjarne Stroustrup, Section 3, From C with Classes to C++; 3.3.1 Minor Changes
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag NBM1BP Edit this page History Report an error Markdown