
Incomputer programming, acomment is text embedded insource code that a translator (compiler orinterpreter) ignores. Generally, a comment is anannotation intended to make the code easier for aprogrammer to understand – often explaining an aspect that is not readily apparent in the program (non-comment) code.[1] For this article,comment refers to the same concept in aprogramming language,markup language,configuration file and any similar context.[2] Somedevelopment tools, other than a source code translator, doparse comments to provide capabilities such asAPIdocument generation,static analysis, andversion control integration. Thesyntax of comments varies by programming language yet there are repeating patterns in the syntax among languages as well as similar aspects related to comment content.
The flexibility supported by comments allows for a wide degree of content style variability. To promote uniformity, style conventions are commonly part of aprogramming style guide. But,best practices are disputed and contradictory.[3][4]
Support for code comments is defined by each programming language. The features differ by language, but there are several common attributes that apply throughout.
Most languages support multi-line block (a.k.a. stream) and/or single line comments. Ablock comment isdelimited with text that marks the start and end of comment text. It can span multiple lines or occupy any part of a line. Some languages allow block comments to be recursively nested inside one another, but others do not.[5][6][7] Aline comment ends at the end of the text line. In modern languages, a line comment starts with a delimiter but some older languages designate a column at which subsequent text is considered comment.[7] Many languages support both block and line comments – using different delimiters for each. For example,C,C++ and their many derivatives support block comments delimited by/* and*/ and line comments delimited by//. Other languages support only one type of comment.[7]
Comments can also be classified as either prologue or inline based on their position and content relative to program code. Aprologue comment is a comment (or group of related comments) located near the top of an associated programming topic, such as before a symbol declaration or at the top of a file. Aninline comment is a comment that is located on the same line as and to the right of program code to which is refers.[8] Both prologue and inline comments can be represented as either line or block comments. For example:
/* * prologue block comment */boolfoo(){returntrue;/* inline block comment */}//// prologue line comment//boolbar(){returnfalse;// inline line comment}
Comments can explain the author's intent –why the code is as it is. Some contend that describingwhat the code does is superfluous. The need to explain thewhat is a sign that it is too complex and should be re-worked.
Comments may explain why a choice was made to write code that is counter to convention or best practice. For example:
' Second variable dim because of server errors produced when reuse form data.' No documentation available on server behavior issue, so just coding around it.vtx=server.mappath("local settings")
The example below explains why aninsertion sort was chosen instead of aquicksort, as the former is, in theory, slower than the latter.
list=[f(b),f(b),f(c),f(d),f(a),...];// Need a stable sort. Besides, the performance really does not matter.insertion_sort(list);
Comments can describe an algorithm aspseudocode. This could be done before writing the code as a first draft. If left in the code, it can simplifycode review by allowing comparison of the resulting code with the intended logic. For example:
/* loop backwards through all elements returned by the server(they should be processed chronologically)*/for(i=(numElementsReturned-0);i>=1;i--){/* process each element's data */updatePattern(i,returnedElements[i]);}
Sometimes code contains a novel or noteworthy solution that warrants an explanatory comment. Such explanations might be lengthy and include diagrams and formal mathematical proofs. This may describe what the code does rather than intent, but may be useful for maintaining the code. This might apply for highly specialized problem domains or rarely used optimizations, constructs or function-calls.[11]
When some aspect of the code is based on information in an external reference, comments link to the reference. For example as a URL or book name and page number.
A common developer practice is tocomment out one or more lines of code. The programmer adds comment syntax that converts program code into comments so that what was executable code will no longer be executed at runtime. Sometimes this technique is used to find the cause of a bug. By systematically commenting out and running parts of the program, the offending source code can be located.
Many IDEs support adding and removing comments with convenientuser interface such as akeyboard shortcut.
Comments can storemetadata about the code. Common metadata includes the name of the original author and subsequent maintainers, dates when first written and modified, link to development and user documentation, and legal information such ascopyright andsoftware license. Rarely,text-encoded. binary data can be included.
Someprogramming tools write metadata into the code as comments.[12] For example, aversion control tool might write metadata such as author, date and version number into each file when it's committed to the repository.[13]
Sometimes information stored in comments is used by development tools other than the translator – the primary tool that consumes the code. This information may include metadata (often used by a documentation generator) or tool configuration.
Somesource code editors support configuration via metadata in comments.[14] One particular example is themodeline feature ofVim which configures tab character handling. For example:
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
AnAPIdocumentation generator parses information from a codebase to generate API documentation. Many support reading information from comments, often parsing metadata, to control the content and formatting of the resulting document.
Although some claim that API documentation can be higher quality when written in a more traditional and manual way, some claim that storing documentation information in code comments simplifies the documenting process, as well as increases the likelihood that the documentation will be kept up to date.[15] Examples includeJavadoc, Ddoc,Doxygen,Visual Expert andPHPDoc. Forms ofdocstring are supported byPython,Lisp,Elixir, andClojure.[16]C#,F# andVisual Basic .NET implement a similar feature called "XML Comments" which are read byIntelliSense from the compiled.NET assembly.[17]
AnASCII artvisualization such as alogo, diagram, orflowchart can be included in a comment.[18]
The following code fragment depicts the process flow of asystem administration script (Windows script file). Although a section marking the code appears as a comment, the diagram is in anXMLCDATA section, which is technically not a comment, but serves the same purpose here.[19] Although this diagram could be in a comment, the example illustrates one instance where the programmer opted not to use a comment as a way of including resources in source code.[19]
<!-- begin: wsf_resource_nodes --><resourceid="ProcessDiagram000"><![CDATA[ HostApp (Main_process) | Vscript.wsf (app_cmd) --> ClientApp (async_run, batch_process) | | V mru.ini (mru_history)]]></resource>
Sometimes, comments describe development processes related to the code. For example, comments might describe how tobuild the code or how to submit changes to thesoftware maintainer.
Occasionally, code that is formatted as a comment is overloaded to convey additional information to the translator, such as conditional comments. As such, syntax that generally indicates a comment can actually represent program code; not comment code. Such syntax may be a practical way to maintain compatibility while adding additional functionality, but some regard such a solution as akludge.[20]
Other examples include interpreterdirectives:
#! – used on the first line of a script to point to the interpreter to be used.The script below for aUnix-like system shows both of these uses:
#!/usr/bin/env python3# -*- coding: UTF-8 -*-print("Testing")
Thegcc compiler (since 2017) looks for a comment in aswitch statement if a case falls-thru to the next case. If an explicit indication of fall-thru is not found, then the compiler issues a warning about a possible coding problem. Inserting such a comment about fall-thru is a long standing convention, and the compiler has codified the practice.[23] For example:
switch(command){caseCMD_SHOW_HELP_AND_EXIT:do_show_help();/* Fall thru */caseCMD_EXIT:do_exit();break;}
To relieve stress or attempt humor, sometimes programmers add comments about the quality of the code, tools, competitors, employers, working conditions, or other arguably unprofessional topics – sometimes usingprofanity.[24][25]
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]
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 orself-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 thedesign by contract approach to programming.
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:
Strings="Wikipedia";/* Assigns the value "Wikipedia" to the variable s. */
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]
As free-form text, comments can be styled in a wide variety of ways. Many prefer a style that is consistent, non-obstructive, easy to modify, and difficult to break. As some claim that a level of consistency is valuable and worthwhile, a consistent commenting style is sometimes agreed upon before a project starts or emerges as development progresses.[34]
The following C fragments show some of diversity in block comment style:
/* This is the comment body.*/
/***************************** * * * This is the comment body. * * * *****************************/
Factors such as personal preference, flexibility of programming tools can influence the commenting style used. For example, the first might be preferred by programmers who use asource code editor that does not automatically format a comment as shown in the second example.
Software consultant and technology commentatorAllen Holub[35] advocates aligning the left edges of comments:[36]
/* This is the style recommended by Holub for C and C++. * It is demonstrated in ''Enough Rope'', in rule 29. */
/* This is another way to do it, also in C. ** It is easier to do in editors that do not automatically indent the second ** through last lines of the comment one space from the first. ** It is also used in Holub's book, in rule 31. */
In many languages, a line comment can follow program code such that the comment isinline and generally describes the code to the left of it. For example, in this Perl:
print$s."\n";# Add a newline character after printing
If a language supports both line and block comments, programming teams may decide upon a convention of when to use which. For example, line comments only for minor comments, and block comments to for higher-level abstractions.
Some comments are categorized with a prefix – atag, codetag[37][38] or token.[39] Some editorshighlight a comment based on its tag.
Commonly used tags include:
For example:
int foo() { // TODO implement}Syntax for comments varies by programming language. There are common patterns used by multiple languages while also a wide range of syntax among the languages in general. To limit the length of this section, some examples are grouped by languages with the same or very similar syntax. Others are for particular languages that have less common syntax.
Many of thecurly brace languages such as C, C++ and their many derivatives delimit a line comment with// and a block comment with/* and*/. Originally, C lacked the line comment, but it was added inC99. Notable languages include: C, C++,C#,D,Java,JavaScript andSwift. For example:
/* * Check if over maximum process limit, but be sure to exclude root. * This is needed to make it possible for login to set per-user * process limit to something lower than processes root is running. */boolisOverMaximumProcessLimit(){// TODO implement}
Some languages, including D[40] and Swift[41], allow block comments to be nested while other do not, including C and C++.
An example of nested blocks in D:
// line comment/* block comment*//+ start of outer block /+ inner block +/ end of outer block +/
An example of nested blocks in Swift:
/* This is the start of the outer comment. /* This is the nested comment. */This is the end of the outer comment. */
A pattern in manyscripting languages is to delimit a line comment with#. Support for a block comment varies. Notable languages include:Bash,Raku,Ruby,Perl,PowerShell,Python andR.
An example in R:
# This is a commentprint("This is not a comment")# This is another comment
A block comment is delimited by=begin and=end that start a line. For example:
puts"not a comment"# this is a commentputs"not a comment"=beginwhatever goes in these linesis just for the human reader=endputs"not a comment"
Instead of a regular block commenting construct, Perl usesliterate programmingplain old documentation (POD) markup.[42] For example:[43]
=item Pod::List-E<gt>new()Create a new list object. Properties may be specified through a hashreference like this: my $list = Pod::List->new({ -start => $., -indent => 4 });=cutsubnew{...}
Raku (previously called Perl 6) uses the same line comments and POD comments asPerl, but adds a configurable block comment type: "multi-line / embedded comments".[44] It starts with#` and then an opening bracket character and ends with the matching closing bracket character.[44] For example:
#`{{ "commenting out" this versiontoggle-case(Str:D $s)Toggles the case of each character in a string: my Str $toggled-string = toggle-case("mY NAME IS mICHAEL!");}}subtoggle-case(Str:D$s)#`( this version of parens is used now ){ ...}
PowerShell supports a block comment delimited by<# and#>. For example:
# Single line comment<# Multi Line Comment #>
Although Python does not provide for block comments[45] a barestring literal represented by a triple-quoted string is often used for this purpose.[46][45] In the examples below, the triple double-quoted strings act like comments, but are also treated asdocstrings:
"""At the top of a file, this is the module docstring"""classMyClass:"""Class docstring"""defmy_method(self):"""Method docstring"""
Markup languages in general vary in comment syntax, but some of the notable internet markup formats such asHTML andXML delimit a block comment with<!-- and--> and provide no line comment support. An example in XML:
<!-- select the context here --><paramname="context"value="public"/>
For compatibility withSGML, double-hyphen (--) is not allowed inside comments.
ColdFusion provides syntax similar to theHTML comment, but uses three dashes instead of two. CodeFusion allows for nested block comments.
In Haskell, a block comment is delimited by{- and-}. For example:
{- this is a commenton more lines -}-- and this is a comment on one lineputStrLn"Wikipedia"-- this is another comment
Haskell also provides aliterate programming method of commenting known as "Bird Style".[47] Lines starting with> are interpreted as code and everything else is considered a comment. One additional requirement is a blank line before and after the code block:
In Bird-style you have to leave a blank before the code.>fact::Integer->Integer>fact0=1>fact(n+1)=(n+1)*factnAnd you have to leave a blank line after the code as well.
Literate programming can also be accomplished viaLaTeX. Example of a definition:
\usepackage{verbatim}\newenvironment{code}{\verbatim}{\endverbatim}
Used as follows:
% the LaTeX source fileThe\verb|fact n| function call computes$n!$ if$n\ge0$, here is a definition:\\\begin{code}fact::Integer->Integerfact0=1fact(n+1)=(n+1)*factn\end{code}Here more explanation using\LaTeX{} markup
Lua supports block comments delimited by--[[ and]][48] For example:
--[[A multi-linelong comment]]
In some variants of SQL, the curly brace language block comment (/**/) is supported. Variants include:Transact-SQL,MySQL,SQLite,PostgreSQL, andOracle.[49][50][51][52][53]
MySQL also supports a line comment delimited by#.
APL uses⍝ ("lamp") for a line comment. For example:
⍝ Now add the numbers:c←a+b⍝ addition
In dialects that have the⊣ ("left") and⊢ ("right") primitives, comments can often beinside or separate statements, in the form of ignored strings:
d←2×c⊣'where'⊢c←a+'bound'⊢b
AppleScript supports both line and block comments. For example:
# line comment (in later versions)(*This program displays a greeting.*)ongreet(myGreeting)display dialogmyGreeting&" world!"endgreet-- Show the greetinggreet("Hello")
Early versions ofBASIC usedREM (short for remark) for a line comment.
10REM This BASIC program shows the use of the PRINT and GOTO Statements.15REM It fills the screen with the phrase "HELLO"20PRINT"HELLO"30GOTO20
In later variations, includingQuick Basic,Q Basic,Visual Basic (VB),VB.NET,VBScript,FreeBASIC andGambas, a line comment is delimited with' (apostrophe). An example in VB.NET:
PublicClassForm1PrivateSubButton1_Click(senderAsObject,eAsEventArgs)HandlesButton1.Click' new style line commentrem old style line comment still supportedMessageBox.Show("Hello, World")' show dialog with a greetingEndSubEndClass
Theexclamation point (!) may be used to mark comments in a Cisco router's configuration mode, however such comments arenot saved tonon-volatile memory (which contains the startup-config), nor are they displayed by the "show run" command.[54][55]
It is possible to inserthuman-readable content that is actually part of the configuration, and may be saved to theNVRAM startup-config via:
! Paste the text below to reroute traffic manuallyconfig tint gi0/2no shutip route 0.0.0.0 0.0.0.0 gi0/2 name ISP2no ip route 0.0.0.0 0.0.0.0 gi0/1 name ISP1int gi0/1shutexit
The following fixed-formFortran code fragment shows that comment syntax is column-oriented. A letterC in the first column causes the entire line to be treated as a comment. InFortran 77, an asterisk in column 1 also indicates a comment.
CC Lines beginning with 'C' in the first (a.k.a. comment) column are commentsCWRITE(6,610) 610FORMAT(12HHELLOWORLD)END
The followingFortran 90 code fragment shows a more modern line comment syntax; text following!.
! A commentprogramcomment_testprint'(A)','Hello world'! also a commentend program
Free-form Fortran, also introduced with Fortran 90, only supports this latter style of comment.
Although not a part of the Fortran Standard, many Fortran compilers offer an optional C-likepreprocessor pass. This can be used to provide block comments:
#if 0Thisisablockcommentspanningmultiplelines.#endifprogramcomment_testprint'(A)','Hello world'! also a commentend program
InMATLAB's programming language, the '%' character indicates a single-line comment. Multi line comments are also available via %{ and %} brackets and can be nested, e.g.
% These are the derivatives for each termd=[0-10];%{ %{ (Example of a nested comment, indentation is for cosmetics (and ignored).) %}Weformthesequence,followingtheTaylorformula.Notethatwe'reoperatingonavector.%}seq=d.*(x-c).^n./(factorial(n))% We add-up to get the Taylor approximationapprox=sum(seq)
Nim delimits a line comment with# and block comments with#[ and]#. Block comments can be nested.
Nim also has documentation comments that use mixedMarkdown andReStructuredText markups.A line documentation comment uses '##' and a block documentation comment uses '##[' and ']##'.The compiler can generateHTML,LaTeX andJSON documentation from the documentation comments.Documentation comments are part of theabstract syntax tree and can be extracted using macros.[56]
## Documentation of the module *ReSTructuredText* and **MarkDown**# This is a comment, but it is not a documentation comment.typeKitten=object## Documentation of typeage:int## Documentation of fieldprocpurr(self:Kitten)=## Documentation of functionecho"Purr Purr"# This is a comment, but it is not a documentation comment.# This is a comment, but it is not a documentation comment.
OCaml supports nestable comments. For example:
codeLine(* comment level 1(*comment level 2*)*)
InPascal andDelphi, a block comment is delimited by{ and}, and as an alternative for computers that do not support these characters,(* and*) are also supported. A line comment is delimited by\\.[57] InNiklaus Wirth's more modern family of languages (includingModula-2 andOberon), comments are delimited by(* and*).[58][59] Comments can be nested. For example:
(* test diagonals *)columnDifference:=testColumn-column;if(row+columnDifference=testRow)or.......
Comments inPHP can be either curly brace style (both line and block), or line delimited with#l. Blocks cannot be nested. Starting in PHP 8, a# only means comment if it's not immediately followed by[. Otherwise, it delimits an attribute, which continues till the next]. For example:
/** * This class contains a sample documentation. * @author Unknown */#[Attribute]classMyAttribute{constVALUE='value';// C++ style line commentprivate$value;# script style line commentpublicfunction__construct($value=null){$this->value=$value;}}
A relatively loose collection of languages use-- for a single line comment. Notable languages include:Ada,Eiffel,Haskell,Lua,SQL andVHDL. Block comment support varies. An example in Ada:
-- the air traffic controller task takes requests for takeoff and landingtasktypeController(My_Runway:Runway_Access)is-- task entries for synchronous message passingentryRequest_Takeoff(ID:inAirplane_ID;Takeoff:outRunway_Access);entryRequest_Approach(ID:inAirplane_ID;Approach:outRunway_Access);endController;
Ininterpreted languages the comments are viewable to theend user of the program. In some cases, such as sections of code that are "commented out", this may present a securityvulnerability.[60]
Triple quotes are treated as regular strings with the exception that they can span multiple lines. By regular strings I mean that if they are not assigned to a variable they will be immediately garbage collected as soon as that code executes. hence are not ignored by the interpreter in the same way that #a comment is.