Examples Comparison Ada APL AppleScript BASIC C Cisco IOS and IOS-XE configuration ColdFusion Fortran IV Fortran 90 Haskell Java JavaScript Lua MATLAB OCaml Pascal Perl Perl 6 PHP PowerShell Python Ruby SQL Swift XML
Security issues
See also
Notes and references
Further reading
External links
{{selfref|For comments in Wikipedia markup, see Wiki markup#Character formatting and COMMENT.}}
In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters.[1][2] The syntax of comments in various programming languages varies considerably.
Comments are sometimes processed in various ways to generate documentation external to the source code itself by documentation generators, or used for integration with source code management systems and other kinds of external programming tools.
The flexibility provided by comments allows for a wide degree of variability, but formal conventions for their use are commonly part of programming style guides.
Overview
Comments are generally formatted as either block comments (also called prologue comments or stream comments) or line comments (also called inline comments).[3]
Block comments delimit a region of source code which may span multiple lines or a part of a single line. This region is specified with a start delimiter and an end delimiter. Some programming languages (such as MATLAB) allow block comments to be recursively nested inside one another, but others (such as Java) do not.[4][5][6]
Line comments either start with a comment delimiter and continue until the end of the line, or in some cases, start at a specific column (character line offset) in the source code, and continue until the end of the line.[6]
Some programming languages employ both block and line comments with different comment delimiters. For example, C++ has block comments delimited by /* and */ that can span multiple lines and line comments delimited by //. Other languages support only one type of comment. For example, Ada comments are line comments: they start with -- and continue to the end of the line.[6]
Uses
How best to make use of comments is subject to dispute; different commentators have offered varied and sometimes opposing viewpoints.[7][8]
There are many different ways of writing comments and many commentators who offer sometimes conflicting advice.[8]
Planning and reviewing
Comments can be used as a form of pseudocode to outline intention prior to writing the actual code. In this case it should explain the logic behind the code rather than the code itself.
(they should be processed chronologically)*/
for (i = (numElementsReturned - 1); i >= 0; i--){
/* process each element's data */ updatePattern(i, returnedElements[i]);
}
If this type of comment is left in, it simplifies the review process by allowing a direct comparison of the code with the intended results. A common logical fallacy is that code that is easy to understand does what it's supposed to do.
Code description
Comments can be used to summarize code or to explain the programmer's intent. According to this school of thought, restating the code in plain English is considered superfluous; the need to re-explain code may be a sign that it is too complex and should be rewritten, or that the naming is bad.
"Don't document bad code – rewrite it."[9]
"Good comments don't repeat the code or explain it. They clarify its intent. Comments should explain, at a higher level of abstraction than the code, what you're trying to do."[10]
Comments may also be used to explain why a block of code does not seem to fit conventions or best practices. This is especially true of projects involving very little development time, or in bug fixing. For example:
' documentation available on server behavior issue, so just coding around it.
vtx = server.mappath("local settings")
Algorithmic description
Sometimes source code contains a novel or noteworthy solution to a specific problem. In such cases, comments may contain an explanation of the methodology. Such explanations may include diagrams and formal mathematical proofs. This may constitute explanation of the code, rather than a clarification of its intent; but others tasked with maintaining the code base may find such explanation crucial. This might especially be true in the case of highly specialized problem domains; or rarely used optimizations, constructs or function-calls.[11]
For example, a programmer may add a comment to explain why an insertion sort was chosen instead of a quicksort, as the former is, in theory, slower than the latter. This could be written as follows:
=== Resource inclusion ===
Logos, diagrams, and flowcharts consisting of ASCII art constructions can be inserted into source code formatted as a comment.[12] Further, copyright notices can be embedded within source code as comments. Binary data may also be encoded in comments through a process known as binary-to-text encoding, although such practice is uncommon and typically relegated to external resource files.
The following code fragment is a simple ASCII diagram depicting the process flow for a system administration script contained in a Windows Script File running under Windows Script Host. Although a section marking the code appears as a comment, the diagram itself actually appears in an XML CDATA section, which is technically considered distinct from comments, but can serve similar purposes.[13]
Although this identical diagram could easily have been included as a comment, the example illustrates one instance where a programmer may opt not to use comments as a way of including resources in source code.[13]
Metadata
{{main | Metadata }}
Comments in a computer program often store metadata about a program file.
In particular, many software maintainers put submission guidelines in comments to help people who read the source code of that program to send any improvements they make back to the maintainer.
Other metadata includes:
the name of the creator of the original version of the program file and the date when the first version was created,
the name of the current maintainer of the program,
the names of other people who have edited the program file so far,
the URL of documentation about how to use the program,
the name of the software license for this program file,
etc.
When an algorithm in some section of the program is based on a description in a book or other reference, comments can be used to give the page number and title of the book or Request for Comments or other reference.
{{anchor|Comment out}}
Debugging
A common developer practice is to comment out a code snippet, meaning to add comment syntax causing that block of code to become a comment, so that it will not be executed in the final program. This may be done to exclude certain pieces of code from the final program, or (more commonly) it can be used to find the source of an error. By systematically commenting out and running parts of the program, the source of an error can be determined, allowing it to be corrected.
An example of commenting out code for exclusion purposes is below:
The above code fragment suggests that the programmer opted to disable the debugging option for some reason.
Many IDEs allow quick adding or removing such comments with single menu options or key combinations. The programmer has only to mark the part of text they want to (un)comment and choose the appropriate option.
Automatic documentation generation
{{main|Documentation generator}}Programming tools sometimes store documentation and metadata in comments.[14] These may include insert positions for automatic header file inclusion, commands to set the file's syntax highlighting mode,[15] or the file's revision number.[16] These functional control comments are also commonly referred to as annotations. Keeping documentation within source code comments is considered as one way to simplify the documentation process, as well as increase the chances that the documentation will be kept up to date with changes in the code.[17]
Examples of documentation generators include the programs Javadoc for use with Java, Ddoc for D, Doxygen for C, C++, Java, IDL, Visual Expert for PL/SQL, Transact-SQL, PowerBuilder and PHPDoc for PHP. Forms of docstring are supported by Python, Lisp, Elixir, and Clojure.[18]
C#, F# and Visual Basic implement a similar feature called "XML Comments" which are read by IntelliSense from the compiled .NET assembly.[19]
Syntax extension
Occasionally syntax elements that were originally intended to be comments are re-purposed to convey additional information to a program, such as "conditional comments".
Such "hot comments" may be the only practical solution that maintains backward-compatibility, but are widely regarded as a kludge.[20]
Directive uses
There are cases where the normal comment characters are co-opted to create a special directive for an editor or interpreter.
Two examples of this directing an interpreter are:
The Unix "shebang" – #! – used on the first line of a script to point to the interpreter to be used.
"Magic comments" identifying the encoding a source file is using,[21] e.g. Python's PEP 263.[22]
The script below for a Unix-like system shows both of these uses:
Somewhat similar is the use of comments in C to communicate to a compiler that a default "fallthough" in a case statement has been done deliberately:
Inserting such a /* Fall thru */ comment for human readers was a already a common convention, but in 2017 the gcc compiler began looking for these (or other indications of deliberate intent), and, if not found, emitting: "warning: this statement may fall through".[23] Compiler-dependent comments which switch off warnings have existed for decades.{{cn|date=February 2019}}
Stress relief
Sometimes programmers will add comments as a way to relieve stress by commenting about development tools, competitors, employers, working conditions, or the quality of the code itself.[24] The occurrence of this phenomenon can be easily seen from online resources that track profanity in source code.[25]
Normative views
There are various normative views and long-standing opinions regarding the proper use of comments in source code.[26][27] Some of these are informal and based on personal preference, while others are published or promulgated as formal guidelines for a particular community.[28]
Need for comments
Experts have varying viewpoints on whether, and when, comments are appropriate in source code.[9][29] Some assert that source code should be written with few comments, on the basis that the source code should be self-explanatory or self-documenting.[9] Others suggest code should be extensively commented (it is not uncommon for over 50% of the non-whitespace characters in source code to be contained within comments).[30][31]
In between these views is the assertion that comments are neither beneficial nor harmful by themselves, and what matters is that they are correct and kept in sync with the source code, and omitted if they are superfluous, excessive, difficult to maintain or otherwise unhelpful.[32][33]
Comments are sometimes used to document contracts in the design by contract approach to programming.
Level of detail
Depending on the intended audience of the code and other considerations, the level of detail and description may vary considerably.
For example, the following Java comment would be suitable in an introductory text designed to teach beginning programming:
This level of detail, however, would not be appropriate in the context of production code, or other situations involving experienced developers. Such rudimentary descriptions are inconsistent with the guideline: "Good comments ... clarify intent."[10] Further, for professional coding environments, the level of detail is ordinarily well-defined to meet a specific performance requirement defined by business operations.[31]
Styles
There are many stylistic alternatives available when considering how comments should appear in source code. For larger projects involving a team of developers, comment styles are either agreed upon before a project starts, or evolve as a matter of convention or need as a project grows. Usually programmers prefer styles that are consistent, non-obstructive, easy to modify, and difficult to break.[34]
Block comment
The following code fragments in C demonstrate just a tiny example of how comments can vary stylistically, while still conveying the same basic information:
Factors such as personal preference, flexibility of programming tools, and other considerations tend to influence the stylistic variants used in source code. For example, Variation Two might be disfavored among programmers who do not have source code editors that can automate the alignment and visual appearance of text in comments.
Software consultant and technology commentator Allen Holub[35] is one expert who advocates aligning the left edges of comments:[36]
The use of /* and */ as block comment delimiters was inherited from PL/I into the B programming language, the immediate predecessor of the C programming language.[37]
Line comments
Line comments generally use an arbitrary delimiter or sequence of tokens to indicate the beginning of a comment, and a newline character to indicate the end of a comment.
In this example, all the text from the ASCII characters // to the end of the line is ignored.
Often such a comment has to begin at far left and extend to the whole line. However in many languages, it is also possible to put a comment inline with a command line, to add a comment to it – as in this Perl example:
If a language allows both line comments and block comments, programming teams may decide upon a convention of using them differently: e.g. line comments only for minor comments, and block comments to describe higher-level abstractions.
Tags
Programmers may use informal tags in comments to assist in indexing common issues. They may then be able to be searched for with common programming tools, such as the Unix grep utility or even syntax-highlighted within text editors. These are sometimes referred to as "codetags"[38][39] or "tokens".[40]
Such tags differ widely, but might include:
BUG – a known bug that should be corrected.
FIXME – should be corrected.
HACK – a workaround.
TODO – something to be done.
UNDONE – a reversal or "roll back" of previous code.
XXX – warn other programmers of problematic or misguiding code
Examples
Comparison
{{main|Comparison of programming languages (syntax)#Comments}}
Typographic conventions to specify comments vary widely. Further, individual programming languages sometimes provide unique variants. For a detailed review, please consult the programming language comparison article.
Ada
The Ada programming language uses '--' to indicate a comment up to the end of the line.
For example:
APL
APL uses ⍝ to indicate a comment up to the end of the line.
For example:
In dialects that have the ⊣ ("left") and ⊢ ("right") primitives, comments can often be inside or separate statements, in the form of ignored strings:
AppleScript
This section of AppleScript code shows the two styles of comments used in that language.
BASIC
In this classic early BASIC code fragment the REM ("REMark") keyword is used to add comments.
In later Microsoft BASICs, including QuickBasic, QBasic, Visual Basic, Visual Basic .NET, and VBScript; and in descendants such as FreeBASIC and Gambas any text on a line after an ' (apostrophe) character is also treated as a comment.
An example in Visual Basic .NET:
C
This C code fragment demonstrates the use of a prologue comment or "block comment" to describe the purpose of a conditional statement. The comment explains key terms and concepts, and includes a short signature by the programmer who authored the code.
Since C99, it has also been possible to use the // syntax from C++, indicating a single-line comment.
Cisco IOS and IOS-XE configuration
The exclamation point (!) may be used to mark comments in a Cisco router's configuration mode, however such comments are not saved to non-volatile memory (which contains the startup-config), nor are they displayed by the "show run" command.[41][42]
It is possible to insert human-readable content that is actually part of the configuration, and may be saved to the NVRAM startup-config via:
The "description" command, used to add a description to the configuration of an interface or of a BGP neighbor
The "name" parameter, to add a remark to a static route