Code Comment
   HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, a comment is text embedded in
source code In computing, source code, or simply code or source, is a plain text computer program written in a programming language. A programmer writes the human readable source code to control the behavior of a computer. Since a computer, at base, only ...
that a translator (
compiler In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
or
interpreter Interpreting is translation from a spoken or signed language into another language, usually in real time to facilitate live communication. It is distinguished from the translation of a written text, which can be more deliberative and make use o ...
) ignores. Generally, a comment is an
annotation An annotation is extra information associated with a particular point in a document or other piece of information. It can be a note that includes a comment or explanation. Annotations are sometimes presented Marginalia, in the margin of book page ...
intended to make the code easier for a
programmer A programmer, computer programmer or coder is an author of computer source code someone with skill in computer programming. The professional titles Software development, ''software developer'' and Software engineering, ''software engineer' ...
to understand often explaining an aspect that is not readily apparent in the program (non-comment) code. For this article, ''comment'' refers to the same concept in a
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
,
markup language A markup language is a Encoding, text-encoding system which specifies the structure and formatting of a document and potentially the relationships among its parts. Markup can control the display of a document or enrich its content to facilitate au ...
,
configuration file A configuration file, a.k.a. config file, is a computer file, file that stores computer data, data used to configure a software system such as an application software, application, a server (computing), server or an operating system. Some applic ...
and any similar context. Some development tools, other than a source code translator, do
parse Parsing, syntax analysis, or syntactic analysis is a process of analyzing a string of symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal grammar by breaking it into parts. The term ''pa ...
comments to provide capabilities such as
API An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build ...
document generation,
static analysis Static analysis, static projection, or static scoring is a simplified analysis wherein the effect of an immediate change to a system is calculated without regard to the longer-term response of the system to that change. If the short-term effect i ...
, and
version control Version control (also known as revision control, source control, and source code management) is the software engineering practice of controlling, organizing, and tracking different versions in history of computer files; primarily source code t ...
integration. The 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 Programming style, also known as coding style, are the conventions and patterns used in writing source code, resulting in a consistent and readable codebase. These conventions often encompass aspects such as indentation, naming conventions, cap ...
guide. But,
best practice A best practice is a method or technique that has been generally accepted as superior to alternatives because it tends to produce superior results. Best practices are used to achieve quality as an alternative to mandatory standards. Best practice ...
s are disputed and contradictory. offers viewpoints on proper use of comments in source code. p. 66. discusses comments and the "Science of Documentation" p. 256.


Common attributes

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 is delimited 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. 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. 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. 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. Both prologue and inline comments can be represented as either line or block comments. For example: /* * prologue block comment; if is about foo() */ bool foo() // // prologue line comment; if is about bar() // bool bar()


Examples of use


Describe intent

Comments can explain the author's intent ''why'' the code is as it is. Some contend that describing ''what'' the code does is superfluous. The need to explain the ''what'' is a sign that it is too complex and should be re-worked. :"Don't document bad code – rewrite it."'' The Elements of Programming Style'', Kernighan & Plauger :"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."'' Code Complete'', McConnell


Highlight unusual practice

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 an insertion sort was chosen instead of a
quicksort Quicksort is an efficient, general-purpose sorting algorithm. Quicksort was developed by British computer scientist Tony Hoare in 1959 and published in 1961. It is still a commonly used algorithm for sorting. Overall, it is slightly faster than ...
, as the former is, in theory, slower than the latter. list = (b), f (b), f (c), f (d), f (a), ... // Need a stable sort. Besides, the performance really does not matter. insertion_sort (list);


Describe algorithm

Comments can describe an algorithm as
pseudocode In computer science, pseudocode is a description of the steps in an algorithm using a mix of conventions of programming languages (like assignment operator, conditional operator, loop) with informal, usually self-explanatory, notation of actio ...
. This could be done before writing the code as a first draft. If left in the code, it can simplify
code review Code review (sometimes referred to as peer review) is a software quality assurance activity in which one or more people examine the source code of a computer program, either after implementation or during the development process. The persons perf ...
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--) 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.


Reference

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.


Comment out

A common developer practice is to comment 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 convenient
user interface In the industrial design field of human–computer interaction, a user interface (UI) is the space where interactions between humans and machines occur. The goal of this interaction is to allow effective operation and control of the machine fro ...
such as a
keyboard shortcut In computing, a keyboard shortcut (also hotkey/hot key or key binding) is a software-based assignment of an action to one or more keys on a computer keyboard. Most Operating system, operating systems and Application software, applications come ...
.


Store metadata

Comments can store
metadata Metadata (or metainformation) is "data that provides information about other data", but not the content of the data itself, such as the text of a message or the image itself. There are many distinct types of metadata, including: * Descriptive ...
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 A copyright is a type of intellectual property that gives its owner the exclusive legal right to copy, distribute, adapt, display, and perform a creative work, usually for a limited time. The creative work may be in a literary, artistic, ...
and
software license A software license is a legal instrument governing the use or redistribution of software. Since the 1970s, software copyright has been recognized in the United States. Despite the copyright being recognized, most companies prefer to sell lic ...
. Some programming tools write metadata into the code as comments. For example, a
version control Version control (also known as revision control, source control, and source code management) is the software engineering practice of controlling, organizing, and tracking different versions in history of computer files; primarily source code t ...
tool might write metadata such as author, date and version number into each file when it's committed to the repository.


Integrate with development tools

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. Some source code editors support configuration via metadata in comments. One particular example is the ''modeline'' feature of Vim which configures tab character handling. For example: # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4


Support documentation generation

An
API An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build ...
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. 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. Examples include
Javadoc Javadoc (also capitalized as JavaDoc or javadoc) is an API documentation generator for the Java programming language. Based on information in Java source code, Javadoc generates documentation formatted as HTML and other formats via extensions. ...
, Ddoc, Doxygen, Visual Expert and PHPDoc. Forms of docstring are supported by Python,
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
,
Elixir An elixir is a sweet liquid used for medical purposes, to be taken orally and intended to cure one's illness. When used as a dosage form, pharmaceutical preparation, an elixir contains at least one active ingredient designed to be taken orall ...
, and
Clojure Clojure (, like ''closure'') is a dynamic programming language, dynamic and functional programming, functional dialect (computing), dialect of the programming language Lisp (programming language), Lisp on the Java (software platform), Java platfo ...
. C#, F# and Visual Basic .NET implement a similar feature called "XML Comments" which are read by
IntelliSense Code completion is an autocompletion feature in many integrated development environments (IDEs) that speeds up the process of coding applications by fixing common mistakes and suggesting lines of code. This usually happens through popups while typ ...
from the compiled
.NET The .NET platform (pronounced as "''dot net"'') is a free and open-source, managed code, managed computer software framework for Microsoft Windows, Windows, Linux, and macOS operating systems. The project is mainly developed by Microsoft emplo ...
assembly.


Visualization

An ASCII art visualization such as a
logo A logo (abbreviation of logotype; ) is a graphic mark, emblem, or symbol used to aid and promote public identification and recognition. It may be of an abstract or figurative design or include the text of the name that it represents, as in ...
, diagram, or
flowchart A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a diagrammatic representation of an algorithm, a step-by-step approach to solving a task. The flowchart shows the steps as boxes of v ...
can be included in a comment. The following code fragment depicts the process flow of a
system administration An IT administrator, system administrator, sysadmin, or admin is a person who is responsible for the upkeep, configuration, and reliable operation of computer systems, especially multi-user computers, such as servers. The system administr ...
script ( Windows script file). Although a section marking the code appears as a comment, the diagram is in an
XML Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing data. It defines a set of rules for encoding electronic document, documents in a format that is both human-readable and Machine-r ...
CDATA section, which is technically not a comment, but serves the same purpose here. Sometimes the difference between a "comment" and other syntax elements of a programming or markup language entails subtle nuances. Niederst indicates one such situation by stating: "Unfortunately, XML software thinks of comments as unimportant information and may simply remove the comments from a document before processing it. To avoid this problem, use an XML CDATA section instead." 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. V script.wsf (app_cmd) --> ClientApp (async_run, batch_process) , , V mru.ini (mru_history) >


Store resource data

Binary data may also be encoded in comments through a process known as
binary-to-text encoding A binary-to-text encoding is code, encoding of data (computing), data in plain text. More precisely, it is an encoding of binary data in a sequence of character (computing), printable characters. These encodings are necessary for transmission of ...
, although such practice is uncommon and typically relegated to external resource files.


Document development process

Sometimes, comments describe development processes related to the code. For example, comments might describe how to build the code or how to submit changes to the software maintainer.


Extend language syntax

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 a
kludge A kludge or kluge () is a workaround or makeshift solution that is clumsy, inelegant, inefficient, difficult to extend, and hard to maintain. This term is used in diverse fields such as computer science, aerospace engineering, Internet slang, ...
. Other examples include interpreter directives: * 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, e.g. Python's PEP 263. The script below for a Unix-like system shows both of these uses: #!/usr/bin/env python3 # -*- coding: UTF-8 -*- print("Testing") The gcc compiler (since 2017) looks for a comment in a
switch statement In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map. Switch statements function ...
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. For example: switch (command)


Relieve stress

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 using
profanity Profanity, also known as swearing, cursing, or cussing, is the usage of notionally word taboo, offensive words for a variety of purposes, including to demonstrate disrespect or negativity, to relieve pain, to express a strong emotion (such a ...
.(see e.g.
Linux Swear Count
.


Normative views

There are various normative views and long-standing opinions regarding the proper use of comments in source code. Some of these are informal and based on personal preference, while others are published or promulgated as formal guidelines for a particular community.


Need for comments

Experts have varying viewpoints on whether, and when, comments are appropriate in source code. 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. Others suggest code should be extensively commented (it is not uncommon for over 50% of the non-
whitespace White space or whitespace may refer to: Technology * Whitespace characters, characters in computing that represent horizontal or vertical space * White spaces (radio), allocated but locally unused radio frequencies * TV White Space Database, a m ...
characters in source code to be contained within comments). Javadoc guidelines specify that comments are crucial to the platform. Further, the appropriate level of detail is fairly well-defined: "We spend time and effort focused on specifying boundary conditions, argument ranges and corner cases rather than defining common programming terms, writing conceptual overviews, and including examples for developers." 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.Non-existent comments can make it difficult to comprehend code, but comments may be detrimental if they are obsolete, redundant, incorrect or otherwise make it more difficult to comprehend the intended purpose for the source code. Comments are sometimes used to document contracts in the
design by contract Design by contract (DbC), also known as contract programming, programming by contract and design-by-contract programming, is an approach for designing software. It prescribes that software designers should define formal, precise and verifiable ...
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: String s = "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." Further, for professional coding environments, the level of detail is ordinarily well defined to meet a specific performance requirement defined by business operations.


Styles

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. 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 a source code editor that does not automatically format a comment as shown in the second example. Software consultant and technology commentator Allen Holub advocates aligning the left edges of comments:Allen Holub, ''Enough Rope to Shoot Yourself in the Foot'', , 1995, McGraw-Hill /* 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 is ''inline'' 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.


Tags

Programmers often use one of select words also known as tags, codetags and tokens to categorize the information in a comment. Programmers may leverage these tags by searching for them via a
text editor A text editor is a type of computer program that edits plain text. An example of such program is "notepad" software (e.g. Windows Notepad). Text editors are provided with operating systems and software development packages, and can be used to c ...
or
grep grep is a command-line utility for searching plaintext datasets for lines that match a regular expression. Its name comes from the ed command g/re/p (global regular expression search and print), which has the same effect. grep was originally de ...
. Some editors highlight comment text based on tags. Commonly used tags include: * BUG, DEBUG — identifies a known bug; maybe implying it should be fixed * FIXME — implies that there is work to do to fix a bug * HACK, BODGE, KLUDGE — marks a solution that might be considered low quality * TODO — describes some work to do * NOTE — relatively general information * UNDONE — a reversal or "roll back" of previous code For example: int foo()


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.


Curly brace languages

Many of the curly 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 in C99. Notable languages include: C, C++, C#, D,
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
,
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
and
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIF ...
. 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. */ bool isOverMaximumProcessLimit() 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: // 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. */


Scripting

A pattern in many
scripting language In computing, a script is a relatively short and simple set of instructions that typically automation, automate an otherwise manual process. The act of writing a script is called scripting. A scripting language or script language is a programming ...
s is to delimit a line comment with #. Support for a block comment varies. Notable languages include: Bash, Raku,
Ruby Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
,
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
,
PowerShell PowerShell is a shell program developed by Microsoft for task automation and configuration management. As is typical for a shell, it provides a command-line interpreter for interactive use and a script interpreter for automation via a langu ...
, Python and R. An example in R: # This is a comment print("This is not a comment") # This is another comment


Block in Ruby

A block comment is delimited by =begin and =end that start a line. For example: 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"


Block in Perl

Instead of a regular block commenting construct, Perl uses literate programming plain old documentation (POD) markup. For example: =item Pod::List-Enew() Create a new list object. Properties may be specified through a hash reference like this: my $list = Pod::List->new(); =cut sub new Raku (previously called Perl 6) uses the same line comments and POD comments as
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
, but adds a configurable block comment type: "multi-line / embedded comments". It starts with #` and then an opening bracket character and ends with the matching closing bracket character. For example: #` sub toggle-case(Str:D $s) #`( this version of parens is used now )


Block in PowerShell

PowerShell supports a block comment delimited by <# and #>. For example: # Single line comment <# Multi Line Comment #>


Block in Python

Although Python does not provide for block comments a bare
string literal string literal or anonymous string is a literal for a string value in the source code of a computer program. Modern programming languages commonly use a quoted sequence of characters, formally "bracketed delimiters", as in x = "foo", where , "foo ...
represented by a triple-quoted string is often used for this purpose. In the examples below, the triple double-quoted strings act like comments, but are also treated as docstrings: """ At the top of a file, this is the module docstring """ class MyClass: """Class docstring""" def my_method(self): """Method docstring"""


Browser markup

Markup languages in general vary in comment syntax, but some of the notable internet markup formats such as
HTML Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets ( ...
and
XML Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing data. It defines a set of rules for encoding electronic document, documents in a format that is both human-readable and Machine-r ...
delimit a block comment with <!-- and --> and provide no line comment support. An example in XML: For compatibility with
SGML The Standard Generalized Markup Language (SGML; International Organization for Standardization, ISO 8879:1986) is a standard for defining generalized markup languages for documents. ISO 8879 Annex A.1 states that generalized markup is "based on t ...
, 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 -- for a single line comment. Notable languages include: Ada, Eiffel,
Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
, Lua,
SQL Structured Query Language (SQL) (pronounced ''S-Q-L''; or alternatively as "sequel") is a domain-specific language used to manage data, especially in a relational database management system (RDBMS). It is particularly useful in handling s ...
and
VHDL VHDL (Very High Speed Integrated Circuit Program, VHSIC Hardware Description Language) is a hardware description language that can model the behavior and structure of Digital electronics, digital systems at multiple levels of abstraction, ran ...
. Block comment support varies. An example in 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;


Block in Haskell

In Haskell, a block comment is delimited by . For example: -- and this is a comment on one line putStrLn "Wikipedia" -- this is another comment Haskell also provides a literate programming method of commenting known as "Bird Style". 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 > fact 0 = 1 > fact (n+1) = (n+1) * fact n And you have to leave a blank line after the code as well. Literate programming can also be accomplished via
LaTeX Latex is an emulsion (stable dispersion) of polymer microparticles in water. Latices are found in nature, but synthetic latices are common as well. In nature, latex is found as a wikt:milky, milky fluid, which is present in 10% of all floweri ...
. Example of a definition: \usepackage \newenvironment Used as follows: % the LaTeX source file The \verb, fact n, function call computes $n!$ if $n\ge 0$, here is a definition:\\ \begin fact :: Integer -> Integer fact 0 = 1 fact (n+1) = (n+1) * fact n \end Here more explanation using \LaTeX markup


Block in Lua

Lua supports block comments delimited by -- and For example: -- A multi-line long comment


Block in SQL

In some variants of SQL, the curly brace language block comment (/**/) is supported. Variants include:
Transact-SQL Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to the SQL (Structured Query Language) used to interact with relational databases. T-SQL expands on the SQL standard to include procedural programming, local variables, vari ...
,
MySQL MySQL () is an Open-source software, open-source relational database management system (RDBMS). Its name is a combination of "My", the name of co-founder Michael Widenius's daughter My, and "SQL", the acronym for Structured Query Language. A rel ...
, SQLite,
PostgreSQL PostgreSQL ( ) also known as Postgres, is a free and open-source software, free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. PostgreSQL features transaction processing, transactions ...
, and
Oracle An oracle is a person or thing considered to provide insight, wise counsel or prophetic predictions, most notably including precognition of the future, inspired by deities. If done through occultic means, it is a form of divination. Descript ...
. MySQL also supports a line comment delimited by #.


Less common syntax


APL

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 be ''inside'' or separate statements, in the form of ignored strings: d←2×c ⊣'where'⊢ c←a+ 'bound'⊢ b


AppleScript

AppleScript AppleScript is a scripting language created by Apple Inc. that facilitates automated control of Mac applications. First introduced in System 7, it is currently included in macOS in a package of automation tools. The term ''AppleScript'' may ...
supports both line and block comments. For example: # line comment (in later versions) (* This program displays a greeting. *) on greet(myGreeting) display dialog myGreeting & " world!" end greet -- Show the greeting greet("Hello")


BASIC

Early versions of
BASIC Basic or BASIC may refer to: Science and technology * BASIC, a computer programming language * Basic (chemistry), having the properties of a base * Basic access authentication, in HTTP Entertainment * Basic (film), ''Basic'' (film), a 2003 film ...
used (short for remark) for a line comment. 10 REM This BASIC program shows the use of the PRINT and GOTO Statements. 15 REM It fills the screen with the phrase "HELLO" 20 PRINT "HELLO" 30 GOTO 20 In later variations, including Quick Basic, Q Basic,
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to: * Visual Basic (.NET), the current version of Visual Basic launched in 2002 which runs on .NET * Visual Basic (classic), the original Visual Basic suppo ...
(VB), VB.NET,
VBScript VBScript (Microsoft Visual Basic Scripting Edition) is a deprecated programming language for scripting on Microsoft Windows using Component Object Model (COM), based on classic Visual Basic and Active Scripting. It was popular with system admi ...
,
FreeBASIC FreeBASIC is a FOSS, free and open source multiplatform compiler and programming language based on BASIC licensed under the GNU General Public License, GNU GPL for Microsoft Windows, protected-mode MS-DOS (DOS extender), Linux, FreeBSD and Xbox ...
and Gambas, a line comment is delimited with ' (apostrophe). An example in VB.NET: Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' new style line comment rem old style line comment still supported MessageBox.Show("Hello, World") ' show dialog with a greeting End Sub End Class


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 Non-volatile memory (NVM) or non-volatile storage is a type of computer memory that can retain stored information even after power is removed. In contrast, volatile memory needs constant power in order to retain data. Non-volatile memory typ ...
(which contains the startup-config), nor are they displayed by the "show run" command. 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 Border Gateway Protocol (BGP) is a standardized exterior gateway protocol designed to exchange routing and reachability information among autonomous system (Internet), autonomous systems (AS) on the Internet. BGP is classified as a path-vect ...
neighbor * The "name" parameter, to add a remark to a static route * The "remark" command in access lists ! Paste the text below to reroute traffic manually config t int gi0/2 no shut ip route 0.0.0.0 0.0.0.0 gi0/2 name ISP2 no ip route 0.0.0.0 0.0.0.0 gi0/1 name ISP1 int gi0/1 shut exit


Fortran

The following fixed-form Fortran code fragment shows that comment syntax is column-oriented. A letter C 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. C C Lines beginning with 'C' in the first (a.k.a. comment) column are comments C WRITE (6,610) 610 FORMAT(12H HELLO WORLD) END The following Fortran 90 code fragment shows a more modern line comment syntax; text following !. ! A comment program comment_test print '(A)', 'Hello world' ! also a comment end 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-like
preprocessor In computer science, a preprocessor (or precompiler) is a Computer program, program that processes its input data to produce output that is used as input in another program. The output is said to be a preprocessed form of the input data, which i ...
pass. This can be used to provide block comments: #if 0 This is a block comment spanning multiple lines. #endif program comment_test print '(A)', 'Hello world' ! also a comment end program


MATLAB

In
MATLAB MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementat ...
's programming language, the '%' character indicates a single-line comment. Multi line comments are also available via % brackets and can be nested, e.g. % These are the derivatives for each term d = -1 0 % seq = d .* (x - c).^n ./(factorial(n)) % We add-up to get the Taylor approximation approx = sum(seq)


Nim

Nim delimits a line comment with # and block comments with # /code> and . Block comments can be nested. Nim also has documentation comments that use mixed
Markdown Markdown is a lightweight markup language for creating formatted text using a plain-text editor. John Gruber created Markdown in 2004 as an easy-to-read markup language. Markdown is widely used for blogging and instant messaging, and also used ...
and ReStructuredText markups. A line documentation comment uses '##' and a block documentation comment uses '## and '#'. The compiler can generate
HTML Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets ( ...
,
LaTeX Latex is an emulsion (stable dispersion) of polymer microparticles in water. Latices are found in nature, but synthetic latices are common as well. In nature, latex is found as a wikt:milky, milky fluid, which is present in 10% of all floweri ...
and
JSON JSON (JavaScript Object Notation, pronounced or ) is an open standard file format and electronic data interchange, data interchange format that uses Human-readable medium and data, human-readable text to store and transmit data objects consi ...
documentation from the documentation comments. Documentation comments are part of the
abstract syntax tree An abstract syntax tree (AST) is a data structure used in computer science to represent the structure of a program or code snippet. It is a tree representation of the abstract syntactic structure of text (often source code) written in a formal ...
and can be extracted using macros. ## Documentation of the module *ReSTructuredText* and **MarkDown** # This is a comment, but it is not a documentation comment. type Kitten = object ## Documentation of type age: int ## Documentation of field proc purr(self: Kitten) = ## Documentation of function echo "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

OCaml OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
supports nestable comments. For example: codeLine(* comment level 1(*comment level 2*)*)


Pascal, Delphi

In Pascal and
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), was an ancient sacred precinct and the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient Classical antiquity, classical world. The A ...
, a block comment is delimited by , and as an alternative for computers that do not support these characters, (* and *) are also supported. A line comment is delimited by \\. In
Niklaus Wirth Niklaus Emil Wirth ( IPA: ) (15 February 1934 – 1 January 2024) was a Swiss computer scientist. He designed several programming languages, including Pascal, and pioneered several classic topics in software engineering. In 1984, he won the Tu ...
's more modern family of languages (including
Modula-2 Modula-2 is a structured, procedural programming language developed between 1977 and 1985/8 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith personal workstation. It w ...
and
Oberon Oberon () is a king of the fairy, fairies in Middle Ages, medieval and Renaissance literature. He is best known as a character in William Shakespeare's play ''A Midsummer Night's Dream'', in which he is King of the Fairies and spouse of Titania ...
), comments are delimited by (* and *).* Comments can be nested. For example: (* test diagonals *) columnDifference := testColumn - column; if (row + columnDifference = testRow) or .......


PHP

Comments in PHP 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 /code>. Otherwise, it delimits an attribute, which continues till the next /code>. For example: /** * This class contains a sample documentation. * @author Unknown */ # ttributeclass MyAttribute


Security issues

In
interpreted language In computer science, an interpreter is a computer program that directly executes instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program. An inter ...
s the comments are viewable to the end user of the program. In some cases, such as sections of code that are "commented out", this may present a security
vulnerability Vulnerability refers to "the quality or state of being exposed to the possibility of being attacked or harmed, either physically or emotionally." The understanding of social and environmental vulnerability, as a methodological approach, involves ...
.


See also

* Comparison of programming languages (syntax)#Comments


Notes and references


Further reading

* Movshovitz-Attias, Dana and Cohen, William W. (2013
Natural Language Models for Predicting Programming Comments
In Association for Computational Linguistics (ACL), 2013.


External links



by Denis Krukovsky
Source Code Documentation as a Live User Manual
by PTLogica

{{DEFAULTSORT:Comment (Computer Programming) Source code Articles with example code Articles with example C code Articles with example Java code Articles with example Perl code Metadata