[[File:CodeCmmt002.svg|thumb|right|300px|[[Java (programming language)|Java]] source code with block comments in <span style="color:#f00;">red</span>, line comments in <span style="color:#0e850e;">green</span> and program code in <span style="color:#00f;"> blue</span>.]]
In [[computer programming]], a '''comment''' is text embedded in [[source code]] that a translator ([[compiler]] or [[interpreter (computing)|interpreter]]) ignores. Generally, a comment is an [[annotation]] intended to make the code easier for a [[programmer]] to understand {{endash}} often explaining an aspect that is not readily apparent in the program (non-comment) code.<ref name="PennyGrubb000">{{cite book | last = Penny Grubb | first = Armstrong Takang | title = Software Maintenance: Concepts and Practice | publisher = World Scientific | year = 2003 | isbn = 978-981-238-426-3 | pages = 7, plese start120–121}}</ref> For this article, ''comment'' refers to the same concept in a [[programming languageslanguage]], [[markup language]]s, [[configuration file]]s and any similar context.<ref>{{cite book | last = Ganguli | first = Madhushree | title = Making Use of Jsp | publisher = Wiley | ___location = New York | year = 2002 | isbn = 978-0-471-21974-3 }}, {{cite book | last = Hewitt | first = Eben | title = Java for Coldfusion Developers | publisher = Pearson Education | ___location = Upper Saddle River | year = 2003 | isbn = 978-0-13-046180-3}}</ref> Some [[development tool]]s, other than a source code translator, do [[parse]] comments to provide capabilities such as [[API]] [[documentation generator|document generation]], [[static analysis]], and [[version control]] integration. The [[comparison of programming languages (syntax)#Comments|syntax 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 a [[programming style]] guide. But, [[best practice]]s are disputed and contradictory.<ref name="Dietrich000">{{cite book
Comments can be processed by some [[development tools]] to provide capabilites such as [[API]] [[documentation generator|document generation]], [[static analysis]], and [[version control]] integration.
The [[comparison of programming languages (syntax)#Comments|syntax of comments]] varies considerably by [[programming language]]. But generally, the flexibility supported by comments allows for a wide degree of style variability. To promote uniformity, conventions for their style are commonly part of a [[programming style]] guide. But, [[best practice]]s are disputed and contradictory.<ref name="Dietrich000">{{cite book
| last = W. R.
| first = Dietrich
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. A '''block comment''' blockis or[[delimiter#Bracket sequencedelimiters|delimited]] ofwith linetext commentsthat located nearmarks the topstart ofand anend associatedof programmingcomment topic,text. suchIt ascan beforespan amultiple symbol declarationlines or atoccupy theany toppart of a file,line. isSome calledlanguages aallow ''prologueblock comment''.comments Ato commentbe thatrecursively isnested on onlyinside one lineanother, usuallybut afterothers programdo code, is called an ''inline comment''not.<ref name="JBDixit000Higham000">{{cite book | last = Dixit | first = J.B. | title = Computer Fundamentals and Programming in C | publisher = Laxmi Publications | year = 2003 | isbn = 978-81-7008-882-0 }}</ref>
A '''block comment''' is [[delimiter#Bracket delimiters|delimited]] with text that marks the start and end of the block. It can span multiple lines or occupy any part of a line. Some languages (such as [[MATLAB]]) allow block comments to be recursively nested inside one another, but others (such as [[Java (programming language)|Java]]) do not.<ref name="Higham000">{{cite book
| title = MATLAB Guide
| first = Desmond
| access-date = 2007-07-24
| date = 2000-03-04
}}</ref> A '''line 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.<ref name="javadude000" /> Many languages support both block and line comments {{endash}} using different delimiters for each. For example, [[C (programming language)|C]], [[C++]] and their many derivatives support block comments delimited by <code>/*</code> and <code>*/</code> and line comments delimited by <code>//</code>. Other languages support only one type of comment.<ref name="javadude000" />
}}</ref>
Comments can also be classified as either prologue or inline based on their position and content relative to program code. A '''prologue 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. An '''inline comment''' is a comment that is located on the same line as and to the right of program code to which is refers.<ref name="JBDixit000">{{cite book | last = Dixit | first = J.B. | title = Computer Fundamentals and Programming in C | publisher = Laxmi Publications | year = 2003 | isbn = 978-81-7008-882-0 }}</ref> Both prologue and inline comments can be represented as either line or block comments. For example:
In modern languages, a '''line comment''' starts with a delimiter and continues until the end of the line. Some older languages designated a column at which subsequent text is considered comment text.<ref name="javadude000" />
<syntaxhighlight lang="c">
Most modern languages support both block and line comments {{endash}} using different delimiters for each. For example, [[C (programming language)|C]], [[C++]] and their many derivatives support block comments delimited by <code>/*</code> and <code>*/</code> and line comments delimited by <code>//</code>. Other languages support only one type of comment.<ref name="javadude000" />
/*
* prologue block comment; if is about foo()
*/
bool foo() {
return true; /* inline block comment; if is about this return */
}
//
// prologue line comment; if is about bar()
//
bool bar() {
return false; // inline line comment; if is about this return
}
</syntaxhighlight>
==Examples of use==
Comments can store [[metadata]] 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 as [[copyright]] and [[software license]].
Some [[programming tools]] write metadata into the code as comments.<ref>See e.g., {{cite book |last=Wynne-Powell |first=Rod |year=2008 |title=Mac OS X for Photographers: Optimized Image Workflow for the Mac User |page=243 |publisher=Focal Press |___location=Oxford |isbn=978-0-240-52027-8 |url=https://archive.org/details/macosxforphotogr0000wynn}}</ref> For example, a [[version control]] tool might write metadata such as author, date and version number into each file when it's commitedcommitted to the repository.<ref>See e.g., {{cite book |last=Berlin |first=Daniel |year=2006 |title=Practical Subversion, Second Edition |page=168 |publisher=APress |___location=Berkeley |isbn=978-1-59059-753-8}}</ref>
=== Integrate with development tools ===
===Support documentation generation===
Sometimes information stored in comments is used by development tools other than the translator {{endash}} the primary tool that consumes the code. This information may include metadata (often used by a documentation generator) or tool configuration.
Some [[source code editor]]s support configuration via metadata in comments.<ref>{{cite book |last=Lamb |first=Linda |year=1998 |title=Learning the VI Editor |publisher=O'Reilly & Associates |___location=Sebastopol |isbn=978-1-56592-426-0 |url=https://archive.org/details/learningvieditor00lamb}}</ref> One particular example is the ''modeline'' feature of [[Vim (text editor)|Vim]] which configures tab character handling. For example:
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
===Support documentation generation===
An [[API]] [[documentation 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.
| publisher=Cambridge University Press
| isbn=978-1-397-80521-8
}}</ref> Examples include [[Javadoc]], [[Ddoc]], [[Doxygen]], [[Visual Expert]] and [[PHPDoc]]. Forms of [[docstring]] are supported by [[Python (programming language)|Python]], [[Lisp (programming language)|Lisp]], [[Elixir (programming language)|Elixir]], and [[Clojure]].<ref>[https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/defn Function definition with docstring in Clojure]</ref> [[C Sharp (programming language)|C#]], [[F Sharp (programming language)|F#]] and [[Visual Basic .NET]] implement a similar feature called "XML Comments" which are read by [[IntelliSense]] from the compiled [[.NET]] assembly.<ref>{{cite book|last=Murach|title=C# 2005|page=56}}</ref>
=== Visualization ===
Sometimes, comments describe development processes related to the code. For example, comments might describe how to [[software build|build]] the code or how to submit changes to the [[software maintainer]].
=== SyntaxExtend extensionlanguage syntax ===
Occasionally, code that is formatted as a comment is overloaded to convey additional information to the translator, such as [[conditional comment]]scomments. 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 a [[kludge]].<ref>[[c2: HotComments]]</ref>
Other examples include interpreter [[Directive (programming)|directives]]:
</syntaxhighlight>
===Relieve stress===
Many editors and [[Integrated development environment|IDE]]s read specially formatted comments. For example, the ''modeline'' feature of [[Vim (text editor)|Vim]]; which changes the handling of tabs. For example:
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 {{endash}} sometimes using [[profanity]].<ref>{{cite web | archive-url=https://web.archive.org/web/20161229170544/http://www.businessinsider.com.au/microsoft-hidden-messages-in-word-and-ms-dos-2014-3?r=US&IR=T | url=https://www.businessinsider.com/microsoft-hidden-messages-in-word-and-ms-dos-2014-3?r=US&IR=T | title=Microsoft Programmers Hid A Bunch Of Profanity In Early Software Code | author=Lisa Eadicicco | date=27 March 2014 | website=[[Business Insider Australia]] | archive-date=29 December 2016 | url-status=live}}</ref><ref name="SwearWords">(see e.g., [http://www.vidarholen.net/contents/wordcount/ Linux Swear Count]).</ref>
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
===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.<ref>{{cite web | archive-url=https://web.archive.org/web/20161229170544/http://www.businessinsider.com.au/microsoft-hidden-messages-in-word-and-ms-dos-2014-3?r=US&IR=T | url=https://www.businessinsider.com/microsoft-hidden-messages-in-word-and-ms-dos-2014-3?r=US&IR=T | title=Microsoft Programmers Hid A Bunch Of Profanity In Early Software Code | author=Lisa Eadicicco | date=27 March 2014 | website=[[Business Insider Australia]] | archive-date=29 December 2016 | url-status=live}}</ref> The occurrence of this phenomenon can be easily seen from online resources that track [[profanity]] in source code.<ref name="SwearWords">(see e.g., [http://www.vidarholen.net/contents/wordcount/ Linux Swear Count]).</ref>
==Normative views==
<syntaxhighlight lang="c">
/***************************\**
* *
* This is the comment body. *
* *
\ *****************************/
</syntaxhighlight>
==Tags==
Programmers often use one of select words {{endash}} also konwnknown as [[tag (metadata)|tags]], codetags<ref>[https://www.python.org/dev/peps/pep-0350/#what-are-codetags "PEP 0350 – Codetags"], Python Software Foundation</ref><ref>[https://medium.com/@eido.askayo/never-forget-anything-before-after-and-while-coding-98d187ae4cf1 "Never Forget Anything Before, After and While Coding"], Using "codetag" comments as productive remainders</ref> and tokens<ref>[https://msdn.microsoft.com/en-us/library/txtwdysk.aspx#tokenscomments "Using the Task List"], msdn.microsoft.com</ref> {{endash}} to categorize the information in a comment. Programmers may leverage these tags by searching for them via a [[text editor]] or [[grep]]. Some editors [[Syntax highlighting|highlight]] comment text based on tags.
Commonly used tags include:
* NOTE — relatively general information
* UNDONE — a reversal or "roll back" of previous code
For example:
int foo() {
// TODO implement
}
==Examples==
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.
===Comparison===
{{main|Comparison of programming languages (syntax)#Comments}}
===Curly brace languages===
Typographic conventions to specify comments vary widely. Further, individual programming languages sometimes provide unique variants.
Many of the [[curly brace language]]s such as C, C++ and their many derivatives delimit a line comment with {{code|//}} and a block comment with {{code|/*}} and {{code|*/}}. Originally, C lacked the line comment, but it was added in [[C99]]. Notable languages include: C, C++, [[C# (programming language)|C#]], [[D (programming language)|D]], [[Java (programming language)|Java]], [[JavaScript]] and [[Swift (programming language)|Swift]]. For example:
<syntaxhighlight lang="c">
====Ada====
/*
* 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.
*/
bool isOverMaximumProcessLimit() {
// TODO implement
}
</syntaxhighlight>
Some languages, including D and Swift, allow blocks to be nested while other do not, including C and C++.
An example of nested blocks in D:
<syntaxhighlight lang="d">
// line comment
/*
block comment
*/
/+ start of outer block
/+ inner block +/
end of outer block +/
</syntaxhighlight>
An example of nested blocks in Swift:
<syntaxhighlight lang="swift">
/* This is the start of the outer comment.
/* This is the nested comment. */
This is the end of the outer comment. */
</syntaxhighlight>
===Scripting===
A pattern in many [[scripting language]]s is to delimit a line comment with <code>#</code>. Support for a block comment varies. Notable languages include: [[Bash (Unix shell)|Bash]], [[Raku (programming language)|Raku]], [[Ruby (programming language)|Ruby]], [[Perl]], [[Windows PowerShell|PowerShell]], [[Python (programming language)|Python]] and [[R (programming language)|R]].
An example in R:
<syntaxhighlight lang="R">
# This is a comment
print("This is not a comment") # This is another comment
</syntaxhighlight>
====Block in Ruby====
A block comment is delimited by <code>=begin</code> and <code>=end</code> that start a line. For example:
<syntaxhighlight lang="ruby">
puts "not a comment"
# this is a comment
puts "not a comment"
=begin
whatever goes in these lines
is just for the human reader
=end
puts "not a comment"
</syntaxhighlight>
====Block in Perl====
Instead of a regular block commenting construct, Perl uses [[literate programming]] [[Plain Old Documentation|plain old documentation (POD)]] markup.<ref>
{{cite web
| title = perlpod – the Plain Old Documentation format
| url = http://perldoc.perl.org/perlpod.html|access-date=2011-09-12
}}
</ref> For example:<ref>
{{cite web
| title = Pod::ParseUtils – helpers for POD parsing and conversion
| url = http://search.cpan.org/~bradapp/PodParser-1.20/lib/Pod/ParseUtils.pm|access-date=2011-09-12
}}</ref>
<syntaxhighlight lang="perl">
=item Pod::List-E<gt>new()
Create a new list object. Properties may be specified through a hash
reference like this:
my $list = Pod::List->new({ -start => $., -indent => 4 });
=cut
sub new {
...
}
</syntaxhighlight>
Raku (previously called Perl 6) uses the same line comments and POD comments as [[Perl]], but adds a configurable block comment type: "multi-line / embedded comments".<ref name=perl6>
{{cite web
| title = Perl 6 Documentation – Syntax (Comments)
| url = https://docs.perl6.org/language/syntax#Comments|access-date=2017-04-06
}}
</ref> It starts with <code>#`</code> and then an opening bracket character and ends with the matching closing bracket character.<ref name=perl6 /> For example:
<syntaxhighlight lang="perl6">
#`{{ "commenting out" this version
toggle-case(Str:D $s)
Toggles the case of each character in a string:
my Str $toggled-string = toggle-case("mY NAME IS mICHAEL!");
}}
sub toggle-case(Str:D $s) #`( this version of parens is used now ){
...
}
</syntaxhighlight>
====Block in PowerShell====
PowerShell supports a block comment delimited by <code><#</code> and <code>#></code>. For example:
<syntaxhighlight lang="powershell">
# Single line comment
<# Multi
Line
Comment #>
</syntaxhighlight>
====Block in Python====
[[Ada (programming language)|Ada]] supports line comments delimited with '--'. It does not support block comments. For example:
Although Python does not provide for block comments<ref name=triple>{{cite web |url=https://www.tutorialdocs.com/tutorial/python3/python3-basic-syntax.html |title=Python 3 Basic Syntax |access-date=25 February 2019 |quote=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. |archive-date=19 August 2021 |archive-url=https://web.archive.org/web/20210819164828/https://www.tutorialdocs.com/tutorial/python3/python3-basic-syntax.html |url-status=dead }}</ref> a bare [[string literal]] represented by a triple-quoted string is often used for this purpose.<ref>[https://twitter.com/gvanrossum/status/112670605505077248 "Python tip: You can use multi-line strings as multi-line comments"], 11 September 2011, Guido van Rossum</ref><ref name=triple/> In the examples below, the triple double-quoted strings act like comments, but are also treated as [[docstring]]s:
<syntaxhighlight lang="python">
"""
At the top of a file, this is the module docstring
"""
class MyClass:
"""Class docstring"""
def my_method(self):
"""Method docstring"""
</syntaxhighlight>
===Browser markup===
Markup languages in general vary in comment syntax, but some of the notable internet markup formats such as [[HTML]] and [[XML]] delimit a block comment with <code><!--</code> and <code>--></code> and provide no line comment support. An example in XML:
<syntaxhighlight lang="xml">
<!-- select the context here -->
<param name="context" value="public" />
</syntaxhighlight>
For compatibility with [[SGML]], double-hyphen (--) is not allowed inside comments.
[[ColdFusion]] provides syntax similar to the [[HTML comment]], but uses three dashes instead of two. CodeFusion allows for nested block comments.
===Double dash===
A relatively loose collection of languages use <code>--</code> for a single line comment. Notable languages include: [[Ada (programming language)|Ada]], [[Eiffel (programming language)|Eiffel]], [[Haskell (programming language)|Haskell]], [[Lua (programming language)|Lua]], [[SQL]] and [[VHDL]]. Block comment support varies. An example in Ada:
<syntaxhighlight lang="ada">
-- the air traffic controller task takes requests for takeoff and landing
task type Controller (My_Runway: Runway_Access) is
-- task entries for synchronous message passing
entry Request_Takeoff (ID: in Airplane_ID; Takeoff: out Runway_Access);
entry Request_Approach(ID: in Airplane_ID; Approach: out Runway_Access);
end Controller;
</syntaxhighlight>
====Block in Haskell====
In Haskell, a block comment is delimited by <code>{-</code> and <code>-}</code>. For example:
<syntaxhighlight lang="Haskell">
{- this is a comment
on more lines -}
-- and this is a comment on one line
putStrLn "Wikipedia" -- this is another comment
</syntaxhighlight>
Haskell also provides a [[literate programming]] method of commenting known as "Bird Style".<ref>{{cite web |url=http://www.haskell.org/haskellwiki/Literate_programming#Bird_Style |title=Literate programming |website=haskell.org}}</ref> Lines starting with <code>></code> are interpreted as code and everything else is considered a comment. One additional requirement is a blank line before and after the code block:
<syntaxhighlight lang="lHaskell">
In Bird-style you have to leave a blank before the code.
> fact :: Integer -> Integer
> fact 0 = 1
> fact (n+1) = (n+1) * fact n
And you have to leave a blank line after the code as well.
</syntaxhighlight>
Literate programming can also be accomplished via [[LaTeX]]. Example of a definition:
<syntaxhighlight lang="lHaskell">
\usepackage{verbatim}
\newenvironment{code}{\verbatim}{\endverbatim}
</syntaxhighlight>
Used as follows:
<syntaxhighlight lang="lhaskell">
% the LaTeX source file
The \verb|fact n| function call computes $n!$ if $n\ge 0$, here is a definition:\\
\begin{code}
fact :: Integer -> Integer
fact 0 = 1
fact (n+1) = (n+1) * fact n
\end{code}
Here more explanation using \LaTeX{} markup
</syntaxhighlight>
====Block in Lua====
Lua supports block comments delimited by <code>--[[</code> and <code>]]</code><ref>{{Cite web|url=http://www.lua.org/pil/1.3.html|title=Programming in Lua 1.3|website=www.Lua.org|access-date=2017-11-08}}</ref> For example:
<syntaxhighlight lang="lua">
--[[A multi-line
long comment
]]
</syntaxhighlight>
==== Block in SQL ====
In some variants of SQL, the curly brace language block comment (<code>/**/</code>) is supported. Variants include: [[Transact-SQL]], [[MySQL]], [[SQLite]], [[PostgreSQL]], and [[Oracle Database|Oracle]].<ref name="MSSQL">{{cite book
| title = Microsoft SQL Server 7
| first = Ronald R.
| last = Talmage
| publisher = Prima Publishing
| year = 1999
| isbn = 978-0-7615-1389-6
| url = https://archive.org/details/microsoftsqlserv00talm
}}</ref><ref name="MySQL">{{cite web | url=https://dev.mysql.com/doc/refman/8.0/en/comments.html | title=MySQL 8.0 Reference Manual | publisher=Oracle Corporation | access-date=January 2, 2020}}</ref><ref name="SQLite">{{cite web | url=https://www.sqlite.org/lang_comment.html | title=SQL As Understood By SQLite | publisher=SQLite Consortium | access-date=January 2, 2020}}</ref><ref name="PostgreSQL">{{cite web | url=https://www.postgresql.org/docs/10/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS | title=PostgreSQL 10.11 Documentation | publisher=The PostgreSQL Global Development Group | access-date=January 2, 2020}}</ref><ref name="Oracle">{{cite web | url=https://docs.oracle.com/cd/B13789_01/server.101/b10759/sql_elements006.htm | title=Oracle® Database SQL Reference | publisher=Oracle Corporation | access-date=January 2, 2020}}</ref>
MySQL also supports a line comment delimited by <code>#</code>.
===Less common syntax===
====APL====
[[APL (programming language)|APL]] uses <code>⍝</code> ("lamp") for a line comment. For example:
<syntaxhighlight lang="apl">
<syntaxhighlight lang="AppleScript">
# line comment (in later versions)
(*
This program displays a greeting.
</syntaxhighlight>
In later variations, including [[Quick Basic]], [[Q Basic]], [[Visual Basic]] (VB), [[Visual Basic .NET|VB.NET]], [[VB ScriptVBScript]], [[FreeBASIC]] and [[Gambas]], a line comment is delimteddelimited with apostrophe<code>'</code> ('apostrophe). An example in Visual Basic VB.NET:
<syntaxhighlight lang="vbnet">
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Thenew followingstyle codeline is executed when the usercomment
'rem clicksold thestyle buttonline incomment thestill program's window.supported
MessageBox.Show("Hello, World") ' show dialog with a greeting
rem comments still exist.
MessageBox.Show("Hello, World") 'Show a pop-up window with a greeting
End Sub
End Class
</syntaxhighlight>
====C====
In [[C (programming language)|C]], [[C++]] and many related languages, the line comment delimiter is {{code|//}} and a block is delimited by {{code|/*}} and {{code|*/}}. Originally, C lacked the line comment, but it was added in [[C99]]. For example:
<syntaxhighlight lang="c">
/*
* Check if we are over our maximum process limit, but be sure to
* exclude root. This is needed to make it possible for login and
* friends to set the per-user process limit to something lower
* than the amount of processes root is running. -- Rik
*/
if (atomic_read(&p->user->processes) >= p->rlim[RLIMIT_NPROC].rlim_cur
&& !capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE))
goto bad_fork_free;
</syntaxhighlight>
</syntaxhighlight>
====ColdFusionFortran====
The following fixed-form [[Fortran]] code fragment shows that comment syntax is column-oriented. A letter <code>C</code> in the first column causes the entire line to be treated as a comment. In [[Fortran 77]], an asterisk in column 1 also indicates a comment.
[[ColdFusion]] uses comments similar to [[HTML comment]]s, but instead of two dashes, it uses three. These comments are caught by the ColdFusion engine and not printed to the browser.
Such comments are nestable.
<syntaxhighlight lang="cfm">
<!--- This prints "Hello World" to the browser.
<!--- This is a comment used inside the first one.
--->
--->
<cfoutput>
Hello World<br />
</cfoutput>
</syntaxhighlight>
====D====
[[D (programming language)|D]] uses C++-style comments, as well as nestable D-style multiline comments, which start with '/+' and end with '+/'.
<syntaxhighlight lang="d">
// This is a single-line comment.
/* This is a multiline comment.
*/
/+ This is a
/+ nested +/
comment +/
</syntaxhighlight>
====Fortran IV====
This [[Fortran IV]] code fragment demonstrates how comments are used in that language, which is very column-oriented. A letter "C" in column 1 causes the entire line to be treated as a comment.
<syntaxhighlight lang="fortranfixed">
C
C Lines that beginbeginning with 'C' (in the first or(a.k.a. 'comment') column) are comments
C
WRITE (6,610)
</syntaxhighlight>
The following [[Fortran|Fortran 90]] code fragment shows a more modern line comment syntax; text following <code>!</code>.
Note that the columns of a line are otherwise treated as four fields: 1 to 5 is the label field, 6 causes the line to be taken as a continuation of the previous statement; and declarations and statements go in 7 to 72.
====Fortran 90====
This [[Fortran]] code fragment demonstrates how comments are used in that language, with the comments themselves describing the basic formatting rules.
<syntaxhighlight lang="Fortran">
! A comment
!* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
!* All characters after an exclamation mark are considered as comments *
!* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
program comment_test
print '(A)', 'Hello world' ! Fortranalso 90a introduced the option for inline comments.comment
end program
</syntaxhighlight>
Free-form Fortran, also introduced with Fortran 90, only supports this latter style of comment.
====Haskell====
Line comments in Haskell start with '--' (two hyphens) until the end of line, and multiple line comments start with '{-' and end with '-}'.
<syntaxhighlight lang="Haskell">
{- this is a comment
on more lines -}
-- and this is a comment on one line
putStrLn "Wikipedia" -- this is another comment
</syntaxhighlight>
Although not a part of the Fortran Standard, many Fortran compilers offer an optional C-like [[preprocessor]] pass. This can be used to provide block comments:
Haskell also provides a [[literate programming]] method of commenting known as "Bird Style".<ref>{{cite web |url=http://www.haskell.org/haskellwiki/Literate_programming#Bird_Style |title=Literate programming |website=haskell.org}}</ref> In this all lines starting with > are interpreted as code, everything else is considered a comment. One additional requirement is that you always leave a blank line before and after the code block:
<syntaxhighlight lang="lHaskellFortran">
#if 0
In Bird-style you have to leave a blank before the code.
This is a block comment spanning
multiple lines.
> fact :: Integer -> Integer
#endif
> fact 0 = 1
program comment_test
> fact (n+1) = (n+1) * fact n
print '(A)', 'Hello world' ! also a comment
end program
And you have to leave a blank line after the code as well.
</syntaxhighlight>
Literate programming can also be done in Haskell, using [[LaTeX]]. The code environment can be used instead of the Richard Bird's style:
In [[LaTeX]] style this is equivalent to the above example, the code environment could be defined in the LaTeX preamble. Here is a simple definition:
<syntaxhighlight lang="lHaskell">
\usepackage{verbatim}
\newenvironment{code}{\verbatim}{\endverbatim}
</syntaxhighlight>
later in
<syntaxhighlight lang="lhaskell">
% the LaTeX source file
The \verb|fact n| function call computes $n!$ if $n\ge 0$, here is a definition:\\
\begin{code}
fact :: Integer -> Integer
fact 0 = 1
fact (n+1) = (n+1) * fact n
\end{code}
Here more explanation using \LaTeX{} markup
</syntaxhighlight>
====Java====
This [[Java (programming language)|Java]] code fragment shows both block and line comments. The block comment is designed to be processed by [[Javadoc]].
<syntaxhighlight lang="java">
/**
* This is a block comment in Java.
* The setToolTipText method registers the text to display in a tool tip.
* The text is displayed when the cursor lingers over the component.
*
* @param text The string to be displayed. If 'text' is null,
* the tool tip is turned off for this component.
*/
public void setToolTipText(String text) {
// This is an inline comment in Java. TODO: Write code for this method.
}
</syntaxhighlight>
====JavaScript====
[[JavaScript (programming language)|JavaScript]] uses // to precede comments and /* */ for multi-line comments.
<syntaxhighlight lang="javascript">
// A single line JavaScript comment
var iNum = 100;
var iTwo = 2; // A comment at the end of line
/*
multi-line
JavaScript comment
*/
</syntaxhighlight>
====Lua====
[[Lua (programming language)|Lua]] uses double-hyphens, <code>--</code>, for single line comments in a similar way to [[Ada (programming language)|Ada]], [[Eiffel (programming language)|Eiffel]], [[Haskell (programming language)|Haskell]], [[SQL]] and [[VHDL]] languages. Lua also has block comments, which start with <code>--[[</code> and run until a closing <code>]]</code> For example:
<syntaxhighlight lang="lua">
--[[A multi-line
long comment
]]
print(20) -- print the result
</syntaxhighlight>
A common technique to comment out a segment of code,<ref>{{Cite web|url=http://www.lua.org/pil/1.3.html|title=Programming in Lua 1.3|website=www.Lua.org|access-date=2017-11-08}}</ref> is to enclose the code between <code>--[[</code> and
<code>--]]</code>, as below:
<syntaxhighlight lang="lua">
--[[
print(10)
--]]
-- no action (commented out)
</syntaxhighlight>
In this case, it's possible to enable the code for use (uncomment-out) by adding a single hyphen to the first line:
<syntaxhighlight lang="lua">
---[[
print(10)
--]]
--> 10
</syntaxhighlight>
The <code>--[[</code> in the first line starts a long comment, and the two hyphens in the last line
are still inside that comment. In the second example, the sequence <code>---[[</code> starts an ordinary, single-line
comment, so that the first and the last lines become independent comments. In this case, the <code>print</code> is
outside comments. In this case, the last line becomes an independent comment, as it starts with <code>--</code>.
====MATLAB====
====Nim====
[[Nim (programming language)|Nim]] usesdelimits thea 'line comment with <code>#'</code> characterand forblock inlinecomments with <code>#[</code> and <code>]#</code>. Block comments can be nested.
Multi-line block comments are opened with '#[' and closed with ']#'.
Multi-line block comments can be nested.
Nim also has documentation comments that use mixed [[Markdown]] and [[ReStructuredText]] markups.
TheA inlineline documentation commentscomment useuses '##' and multi-linea block documentation commentscomment are opened withuses '##[' and closed with ']##'.
The compiler can generate [[HTML]], [[LaTeX]] and [[JSON]] documentation from the documentation comments.
Documentation comments are part of the [[abstract syntax tree]] and can be extracted using macros.<ref>[https://nim-lang.github.io/Nim/macros.html#extractDocCommentsAndRunnables%2CNimNode macros.extractDocCommentsAndRunnables]</ref>
====OCaml====
[[OCaml]] supports nestable comments. For exmapleexample:
<syntaxhighlight lang="ocaml">
codeLine(* comment level 1(*comment level 2*)*)
====Pascal, Delphi====
In [[Pascal (programming language)|Pascal]] and [[Delphi (software)|Delphi]], a block comment is delimited by <code>{</code> and <code>}</code>, and as an alternative for computers that do not support these characters, <code>(*</code> and <code>*)</code> are also supported. A line comment is delimited by <code>\\</code>.<ref>{{cite book|author=Kathleen Jensen, Niklaus Wirth|year=1985|title=Pascal User Manual and Report|publisher=Springer-Verlag|isbn=0-387-96048-1}}</ref> In [[Niklaus Wirth]]'s more modern family of languages (including [[Modula-2]] and [[Oberon (programming language)|Oberon]]), comments are delimited by <code>(*</code> and <code>*)</code>.<ref>{{cite book|author=Niklaus Wirth|year=1983|title=Programming in Modula-2|publisher=Springer-Verlag|isbn=0-387-15078-1}}</ref><ref>*{{cite book|author=Martin Reiser, Niklaus Wirth|year=1992|title=Programming in Oberon|publisher=Addison-Wesley|isbn=0-201-56543-9}}</ref> Comments can be nested. For example:
In [[Pascal (programming language)|Pascal]] and [[Delphi (software)|Delphi]], comments are delimited by '{ ... }'. Comment lines can also start with '\\' .
As an alternative, for computers that do not support these characters, '(* ... *)' are allowed.<ref>{{cite book|author=Kathleen Jensen, Niklaus Wirth|year=1985|title=Pascal User Manual and Report|publisher=Springer-Verlag|isbn=0-387-96048-1}}</ref> In [[Niklaus Wirth]]'s more modern family of languages (including [[Modula-2]] and [[Oberon (programming language)|Oberon]]), comments are delimited by '(* ... *)'.<ref>{{cite book|author=Niklaus Wirth|year=1983|title=Programming in Modula-2|publisher=Springer-Verlag|isbn=0-387-15078-1}}</ref><ref>*{{cite book|author=Martin Reiser, Niklaus Wirth|year=1992|title=Programming in Oberon|publisher=Addison-Wesley|isbn=0-201-56543-9}}</ref> Comments can be nested. // can be included in a {} and {} can be included in a (**). For example:
<syntaxhighlight lang="pascal">
if (row + columnDifference = testRow) or
.......
</syntaxhighlight>
====Perl====
Line comments in [[Perl]], and many other [[scripting language]]s, begin with a hash (#) symbol.
<syntaxhighlight lang="perl">
# A simple example
#
my $s = "Wikipedia"; # Sets the variable s to "Wikipedia".
print $s . "\n"; # Add a newline character after printing
</syntaxhighlight>
Instead of a regular block commenting construct, Perl uses [[Plain Old Documentation]], a markup language for [[literate programming]],<ref>
{{cite web
| title = perlpod – the Plain Old Documentation format
| url = http://perldoc.perl.org/perlpod.html|access-date=2011-09-12
}}
</ref> for instance:<ref>
{{cite web
| title = Pod::ParseUtils – helpers for POD parsing and conversion
| url = http://search.cpan.org/~bradapp/PodParser-1.20/lib/Pod/ParseUtils.pm|access-date=2011-09-12
}}</ref>
<syntaxhighlight lang="perl">
=item Pod::List-E<gt>new()
Create a new list object. Properties may be specified through a hash
reference like this:
my $list = Pod::List->new({ -start => $., -indent => 4 });
See the individual methods/properties for details.
=cut
sub new {
my $this = shift;
my $class = ref($this) || $this;
my %params = @_;
my $self = {%params};
bless $self, $class;
$self->initialize();
return $self;
}
</syntaxhighlight>
====R====
[[R (programming language)|R]] only supports inline comments started by the hash (#) character.
<syntaxhighlight lang="R">
# This is a comment
print("This is not a comment") # This is another comment
</syntaxhighlight>
====Raku====
[[Raku (programming language)|Raku]] (previously called Perl 6) uses the same line comments and POD Documentation comments as regular [[Perl]] (see Perl section above), but adds a configurable block comment type: "multi-line / embedded comments".<ref name=perl6>
{{cite web
| title = Perl 6 Documentation – Syntax (Comments)
| url = https://docs.perl6.org/language/syntax#Comments|access-date=2017-04-06
}}
</ref>
These start with a hash character, followed by a backtick, and then some opening bracketing character, and end with the matching closing bracketing character.<ref name=perl6 /> The content can not only span multiple lines, but can also be embedded inline.
<syntaxhighlight lang="perl6">
#`{{ "commenting out" this version
toggle-case(Str:D $s)
Toggles the case of each character in a string:
my Str $toggled-string = toggle-case("mY NAME IS mICHAEL!");
}}
sub toggle-case(Str:D $s) #`( this version of parens is used now ){
...
}
</syntaxhighlight>
====PHP====
Comments in [[PHP]] can be either incurly C++brace style (both inlineline and block), or useline hashesdelimited with <code>#</code>l. [[PHPDoc]]Blocks iscannot be nested. Starting in PHP 8, a style<code>#</code> adaptedonly frommeans Javadoccomment andif isit's anot commonimmediately standardfollowed forby documenting<code>[</code>. PHPOtherwise, it delimits an attribute, which continues till the next <code>]</code>. For example:
Starting in PHP 8, the # sign can only mean a comment if it's not immediately followed by '['. Otherwise, it will mean a function attribute, which runs until ']':
<syntaxhighlight lang="php">
/**
* This class contains a sample documentation.
*
* @author Unknown
*/
class MyAttribute {
const VALUE = 'value';
// ThisC++ isstyle an inlineline comment. It starts with '//', like in C++.
private $value;
# Thisscript is a Unix-style inlineline comment, which starts with '#'.
public function __construct($value = null) {
$this->value = $value;
}
/*
This is a multiline comment.
These comments cannot be nested.
*/
}
</syntaxhighlight>
====PowerShell====
Comments in [[Windows PowerShell]]
<syntaxhighlight lang="powershell">
# Single line comment
Write-Host "Hello, World!"
<# Multi
Line
Comment #>
Write-Host "Goodbye, world!"
</syntaxhighlight>
====Python====
Line comments in [[Python (programming language)|Python]] are delimiated by the hash (#) character. For example:
<syntaxhighlight lang="python">
# This program prints "Hello World" to the screen
print("Hello World!") # Note the new syntax
</syntaxhighlight>
Python does not provide for block comments<ref name=triple>{{cite web |url=https://www.tutorialdocs.com/tutorial/python3/python3-basic-syntax.html |title=Python 3 Basic Syntax |access-date=25 February 2019 |quote=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. |archive-date=19 August 2021 |archive-url=https://web.archive.org/web/20210819164828/https://www.tutorialdocs.com/tutorial/python3/python3-basic-syntax.html |url-status=dead }}</ref> but a bare [[string literal]] represented by a triple-quoted string can be and often is used for this purpose.<ref>[https://twitter.com/gvanrossum/status/112670605505077248 "Python tip: You can use multi-line strings as multi-line comments"], 11 September 2011, Guido van Rossum</ref><ref name=triple/> In the examples below, the triple double-quoted strings act like comments, but are also treated as [[docstring]]s:
<syntaxhighlight lang="python">
"""
Assuming this is file mymodule.py, then this string, being the
first statement in the file, will become the "mymodule" module's
docstring when the file is imported.
"""
class MyClass:
"""The class's docstring"""
def my_method(self):
"""The method's docstring"""
def my_function():
"""The function's docstring"""
</syntaxhighlight>
====Ruby====
Inline comments in [[Ruby (programming language)|Ruby]] start with the # character.
To create a multiline comment, one must place "=begin" at the start of a line, and then everything until "=end" that starts a line is ignored. Including a space after the equals sign in this case throws a syntax error.
<syntaxhighlight lang="ruby">
puts "This is not a comment"
# this is a comment
puts "This is not a comment"
=begin
whatever goes in these lines
is just for the human reader
=end
puts "This is not a comment"
</syntaxhighlight>
==== SQL ====
Standard comments in SQL are in single-line-only form, using two dashes:
<syntaxhighlight lang="sql">
-- This is a single line comment
-- followed by a second line
SELECT COUNT(*)
FROM Authors
WHERE Authors.name = 'Smith'; -- Note: we only want 'smith'
-- this comment appears after SQL code
</syntaxhighlight>
Alternatively, a comment format syntax identical to the "block comment" style used in the syntax for C and Java is supported by [[Transact-SQL]], [[MySQL]], [[SQLite]], [[PostgreSQL]], and [[Oracle Database|Oracle]].<ref name="MSSQL">{{cite book
| title = Microsoft SQL Server 7
| first = Ronald R.
| last = Talmage
| publisher = Prima Publishing
| year = 1999
| isbn = 978-0-7615-1389-6
| url = https://archive.org/details/microsoftsqlserv00talm
}}</ref><ref name="MySQL">{{cite web | url=https://dev.mysql.com/doc/refman/8.0/en/comments.html | title=MySQL 8.0 Reference Manual | publisher=Oracle Corporation | access-date=January 2, 2020}}</ref><ref name="SQLite">{{cite web | url=https://www.sqlite.org/lang_comment.html | title=SQL As Understood By SQLite | publisher=SQLite Consortium | access-date=January 2, 2020}}</ref><ref name="PostgreSQL">{{cite web | url=https://www.postgresql.org/docs/10/sql-syntax-lexical.html#SQL-SYNTAX-COMMENTS | title=PostgreSQL 10.11 Documentation | publisher=The PostgreSQL Global Development Group | access-date=January 2, 2020}}</ref><ref name="Oracle">{{cite web | url=https://docs.oracle.com/cd/B13789_01/server.101/b10759/sql_elements006.htm | title=Oracle® Database SQL Reference | publisher=Oracle Corporation | access-date=January 2, 2020}}</ref>
MySQL also supports comments from the hash (#) character to the end of the line.
==== Swift ====
In [[Swift (programming language)|Swift]], line comments begin {{code|//}}. Block comments are delimited by {{code|/*}}(/*) and {{code|*/}}. For example:
<syntaxhighlight lang="swift">
// This is a comment.
/* This is also a comment
but is written over multiple lines. */
</syntaxhighlight>
Block comments can be nested. For example:
<syntaxhighlight lang="swift">
/* This is the start of the outer comment.
/* This is the nested comment. */
This is the end of the outer comment. */
</syntaxhighlight>
====XML and HTML====
A block comment in [[XML]] and [[HTML]] is delimited by
<code><!--</code> and <code>--></code>. Line comment is not supported. For example,
<syntaxhighlight lang="xml">
<!-- select the context here -->
<param name="context" value="public" />
</syntaxhighlight>
For compatibility with [[SGML]], double-hyphen (--) is not allowed inside comments.
==Security issues==
==See also==
* [[Comparison of programming languages (syntax)#Comments]]
* [[Docstring]], a specific type of comment that is parsed and retained throughout the runtime of the program.
* [[Shebang (Unix)|Shebang]], the use of ''#!'' as an interpreter directive in scripts on Unix-like systems
* [[HTML comment tag]]
* [[Literate programming]], alternative documentation [[programming paradigm|paradigm]]
* [[Comparison of programming languages (syntax)#Comments|Syntax of comments]] in various programming languages
* [[COMMENT (CONFIG.SYS directive)]]
* [[REM (CONFIG.SYS directive)]]
==Notes and references==
|