HOME

TheInfoList



OR:

In computer programming, a comment is a programmer-readable explanation or ''
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 in the margin of book pages. For anno ...
'' in the
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the ...
of a
computer program A computer program is a sequence or set of instructions in a programming language for a computer to execute. Computer programs are one component of software, which also includes documentation and other intangible components. A computer prog ...
. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs tha ...
s and
interpreters Interpreting is a translational activity in which one produces a first and final target-language output on the basis of a one-time exposure to an expression in a source language. The most common two modes of interpreting are simultaneous inter ...
.Source code can be divided into ''program code'' (which consists of machine-translatable instructions); and ''comments'' (which include human-readable notes and other kinds of annotations in support of the program code). The syntax of comments in various programming languages varies considerably. Comments are sometimes also processed in various ways to generate documentation external to the source code itself by
documentation generator A documentation generator is a programming tool that generates software documentation intended for programmers ( API documentation) or end users (end-user guide), or both, from a set of source code files, and in some cases, binary files. Some gener ...
s, or used for integration with source code management systems and other kinds of external
programming tool A programming tool or software development tool is a computer program that software developers use to create, debug, maintain, or otherwise support other programs and applications. The term usually refers to relatively simple programs, that can ...
s. The flexibility provided by comments allows for a wide degree of variability, but formal conventions for their use are commonly part of programming style guides.


Overview

Comments are generally formatted as either ''block comments'' (also called ''prologue comments'' or ''stream comments'') or ''line comments'' (also called ''inline comments''). Block comments delimit a region of source code which may span multiple lines or a part of a single line. This region is specified with a ''start'' delimiter and an ''end'' delimiter. Some programming languages (such as
MATLAB 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, implementatio ...
) allow block comments to be recursively nested inside one another, but others (such as
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
) do not. Line comments either start with a comment delimiter and continue until the end of the line, or in some cases, start at a specific column (character line offset) in the source code, and continue until the end of the line. Some programming languages employ both block and line comments with different comment delimiters. For example, C++ has block comments delimited by /* and */ that can span multiple lines and line comments delimited by //. Other languages support only one type of comment. For example, Ada comments are line comments: they start with -- and continue to the end of the line.


Uses

How best to make use of comments is subject to dispute; different commentators have offered varied and sometimes opposing viewpoints. offers viewpoints on proper use of comments in source code. p. 66. discusses comments and the "Science of Documentation" p. 256. There are many different ways of writing comments and many commentators offer conflicting advice.


Planning and reviewing

Comments can be used as a form of
pseudocode In computer science, pseudocode is a plain language description of the steps in an algorithm or another system. Pseudocode often uses structural conventions of a normal programming language, but is intended for human reading rather than machine re ...
to outline intention prior to writing the actual code. In this case it should explain the logic behind the code rather than the code itself. /* loop backwards through all elements returned by the server (they should be processed chronologically)*/ for (i = (numElementsReturned - 1); i >= 0; i--) If this type of comment is left in, it simplifies the review process by allowing a direct comparison of the code with the intended results. A common logical fallacy is that code that is easy to understand does what it's ''supposed'' to do.


Code description

Comments can be used to summarize code or to explain the programmer's intent. According to this school of thought, restating the code in plain English is considered superfluous; the need to re-explain code may be a sign that it is too complex and should be rewritten, or that the naming is bad. :"Don't document bad code – rewrite it."'' 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 ''Code Complete'' is a software development book, written by Steve McConnell and published in 1993 by Microsoft Press, encouraging developers to continue past code-and-fix programming and the big design up front and waterfall models. It is al ...
'', McConnell
Comments may also be used to explain why a block of code does not seem to fit conventions or best practices. This is especially true of projects involving very little development time, or in bug fixing. For example: ' 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")


Algorithmic description

Sometimes source code contains a novel or noteworthy solution to a specific problem. In such cases, comments may contain an explanation of the methodology. Such explanations may include diagrams and formal mathematical proofs. This may constitute explanation of the code, rather than a clarification of its intent; but others tasked with maintaining the code base may find such explanation crucial. This might especially be true in the case of highly specialized problem domains; or rarely used optimizations, constructs or function-calls. For example, a programmer may add a comment to explain why an
insertion sort Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time by comparisons. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. H ...
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. This could be written as follows: list = (b), f (b), f (c), f (d), f (a), ... // Need a stable sort. Besides, the performance really does not matter. insertion_sort (list);


Resource inclusion

Logos, diagrams, and flowcharts consisting of
ASCII art ASCII art is a graphic design technique that uses computers for presentation and consists of pictures pieced together from the 95 printable (from a total of 128) character (computing), characters defined by the ASCII Standard from 1963 an ...
constructions can be inserted into source code formatted as a comment. Further,
copyright A copyright is a type of intellectual property that gives its owner the exclusive 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, education ...
notices can be embedded within source code as comments. Binary data may also be encoded in comments through a process known as binary-to-text encoding, although such practice is uncommon and typically relegated to external resource files. The following code fragment is a simple ASCII diagram depicting the process flow for a
system administration A system administrator, or 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 administrator seeks to en ...
script contained in a
Windows Script File A Windows Script File (WSF) is a file type used by the Microsoft Windows Script Host. It allows mixing the scripting languages JScript and VBScript within a single file, or other scripting languages such as Perl, Object REXX, Python, or Kixtart i ...
running under
Windows Script Host The Microsoft Windows Script Host (WSH) (formerly named Windows Scripting Host) is an automation technology for Microsoft Windows operating systems that provides scripting abilities comparable to batch files, but with a wider range of supported ...
. Although a section marking the code appears as a comment, the diagram itself actually appears in an XML CDATA section, which is technically considered distinct from comments, but can serve similar purposes.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." V script.wsf (app_cmd) --> ClientApp (async_run, batch_process) , , V mru.ini (mru_history) > Although this identical diagram could easily have been included as a comment, the example illustrates one instance where a programmer may opt not to use comments as a way of including resources in source code.


Metadata

Comments in a computer program often store metadata about a program file. In particular, many
software maintainer In free and open source software and inner source software, a software maintainer or package maintainer is usually one or more people who build source code into a binary package for distribution, commit patches, or organize code in a source re ...
s put submission guidelines in comments to help people who read the source code of that program to send any improvements they make back to the maintainer. Other metadata includes: the name of the creator of the original version of the program file and the date when the first version was created, the name of the current maintainer of the program, the names of other people who have edited the program file so far, the URL of documentation about how to use the program, the name of the
software license A software license is a legal instrument (usually by way of contract law, with or without printed material) governing the use or redistribution of software. Under United States copyright law, all software is copyright protected, in both sourc ...
for this program file, etc. When an algorithm in some section of the program is based on a description in a book or other reference, comments can be used to give the page number and title of the book or
Request for Comments A Request for Comments (RFC) is a publication in a series from the principal technical development and standards-setting bodies for the Internet, most prominently the Internet Engineering Task Force (IETF). An RFC is authored by individuals or g ...
or other reference.


Debugging

A common developer practice is to ''comment out'' a code snippet, meaning to add comment syntax causing that block of code to become a comment, so that it will not be executed in the final program. This may be done to exclude certain pieces of code from the final program, or (more commonly) it can be used to find the source of an error. By systematically commenting out and running parts of the program, the source of an error can be determined, allowing it to be corrected. Many IDEs allow quick adding or removing such comments with single menu options or key combinations. The programmer has only to mark the part of text they want to (un)comment and choose the appropriate option.


Automatic documentation generation

Programming tool A programming tool or software development tool is a computer program that software developers use to create, debug, maintain, or otherwise support other programs and applications. The term usually refers to relatively simple programs, that can ...
s sometimes store documentation and
metadata Metadata is " data that provides information about other data", but not the content of the data, such as the text of a message or the image itself. There are many distinct types of metadata, including: * Descriptive metadata – the descriptive ...
in comments. These may include insert positions for automatic header file inclusion, commands to set the file's
syntax highlighting Syntax highlighting is a feature of text editors that are used for programming, scripting, or markup languages, such as HTML. The feature displays text, especially source code, in different colours and fonts according to the category of terms. ...
mode, or the file's revision number. These functional control comments are also commonly referred to as
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 in the margin of book pages. For anno ...
s. Keeping documentation within source code comments is considered as one way to simplify the documentation process, as well as increase the chances that the documentation will be kept up to date with changes in the code. Examples of documentation generators include the programs
Javadoc Javadoc (originally cased JavaDoc) is a documentation generator created by Sun Microsystems for the Java language (now owned by Oracle Corporation) for generating API documentation in HTML format from Java source code. The HTML format is used for ...
for use with
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, Ddoc for D,
Doxygen Doxygen ( ) is a documentation generator and static analysis tool for software source trees. When used as a documentation generator, Doxygen extracts information from specially-formatted comments within the code. When used for analysis, Doxygen ...
for C, C++, Java, IDL, Visual Expert for
PL/SQL PL/SQL (Procedural Language for SQL) is Oracle Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is available in Oracle Database (since version 6 - stored PL/SQL procedures/functions/packages/triggers sinc ...
,
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 ...
,
PowerBuilder PowerBuilder is an integrated development environment owned by SAP since the acquisition of Sybase in 2010. On July 5, 2016, SAP and Appeon entered into an agreement whereby Appeon, an independent company, would be responsible for developing, se ...
and PHPDoc for
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
. Forms of
docstring In programming, a docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, or even specifically formatted comments like docblocks, docst ...
are supported by Python,
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lispin ...
,
Elixir ELIXIR (the European life-sciences Infrastructure for biological Information) is an initiative that will allow life science laboratories across Europe to share and store their research data as part of an organised network. Its goal is to bring t ...
, and
Clojure Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is com ...
. C#, F# and
Visual Basic .NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Vi ...
implement a similar feature called "XML Comments" which are read by
IntelliSense Intelligent code completion is a context-aware code completion feature in some programming environments that speeds up the process of coding applications by reducing typos and other common mistakes. Attempts at this are usually done through auto-co ...
from the compiled .NET assembly.


Syntax extension

Occasionally syntax elements that were originally intended to be comments are re-purposed to convey additional information to a program, such as "
conditional comment Conditional comments are conditional statements interpreted by Microsoft Internet Explorer versions 5 through 9 in HTML source code. They can be used to provide and hide code to and from these versions of Internet Explorer. Conditional comments ...
s". Such "hot comments" may be the only practical solution that maintains backward-compatibility, but are widely regarded as a
kludge A kludge or kluge () is a workaround or quick-and-dirty 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 sl ...
.


Directive uses

There are cases where the normal comment characters are co-opted to create a special directive for an editor or interpreter. Two examples of this directing an interpreter are: * The Unix " shebang" – #! – used on the first line of a script to point to the interpreter to be used. * "Magic comments" identifying the encoding a source file is using, 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") Somewhat similar is the use of comments in C to communicate to a compiler that a default "fallthrough" in a case statement has been done deliberately: switch (command) Inserting such a /* Fall thru */ comment for human readers was already a common convention, but in 2017 the gcc compiler began looking for these (or other indications of deliberate intent), and, if not found, emitting: "warning: this statement may fall through". Many editors and IDEs will read specially formatted comments. For example, the "modeline" feature of Vim; which would change its handling of tabs while editing a source with this comment included near the top of the file: # 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. The occurrence of this phenomenon can be easily seen from online resources that track
profanity Profanity, also known as cursing, cussing, swearing, bad language, foul language, obscenities, expletives or vulgarism, is a socially offensive use of language. Accordingly, profanity is language use that is sometimes deemed impolite, ru ...
in source code.(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 In computer programming, self-documenting (or self-describing) source code and user interfaces follow naming conventions and structured programming conventions that enable use of the system without prior specific knowledge. In web development, s ...
. 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 mec ...
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 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

There are many stylistic alternatives available when considering how comments should appear in source code. For larger projects involving a team of developers, comment styles are either agreed upon before a project starts, or evolve as a matter of convention or need as a project grows. Usually programmers prefer styles that are consistent, non-obstructive, easy to modify, and difficult to break.


Block comment

The following code fragments in C demonstrate just a tiny example of how comments can vary stylistically, while still conveying the same basic information: /* This is the comment body. Variation One. */ /***************************\ * * * This is the comment body. * * Variation Two. * * * \***************************/ Factors such as personal preference, flexibility of programming tools, and other considerations tend to influence the stylistic variants used in source code. For example, Variation Two might be disfavored among programmers who do not have
source code editor A source-code editor is a text editor program designed specifically for editing source code of computer programs. It may be a standalone application or it may be built into an integrated development environment (IDE) or web browser. Source-code ed ...
s that can automate the alignment and visual appearance of text in comments. Software consultant and technology commentator Allen Holub is one expert who 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. */ The use of /* and */ as block comment delimiters was inherited from PL/I into the B programming language, the immediate predecessor of the C programming language.


Line comments

Line comments generally use an arbitrary
delimiter A delimiter is a sequence of one or more characters for specifying the boundary between separate, independent regions in plain text, mathematical expressions or other data streams. An example of a delimiter is the comma character, which acts ...
or sequence of tokens to indicate the beginning of a comment, and a
newline Newline (frequently called line ending, end of line (EOL), next line (NEL) or line break) is a control character or sequence of control characters in character encoding specifications such as ASCII, EBCDIC, Unicode, etc. This character, or a ...
character to indicate the end of a comment. In this example, all the text from the ASCII characters // to the end of the line is ignored. // ------------------------- // This is the comment body. // ------------------------- Often such a comment has to begin at far left and extend to the whole line. However, in many languages, it is also possible to put a comment ''inline'' with a command line, to add a comment to it – as in this Perl example: print $s . "\n"; # Add a newline character after printing If a language allows both line comments and block comments, programming teams may decide upon a convention of using them differently: e.g. line comments only for minor comments, and block comments to describe higher-level abstractions.


Tags

Programmers may use informal tags in comments to assist in indexing common issues. They may then be able to be searched for with common programming tools, such as the
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, an ...
grep grep is a command-line utility for searching plain-text data sets for lines that match a regular expression. Its name comes from the ed command ''g/re/p'' (''globally search for a regular expression and print matching lines''), which has the sa ...
utility or even syntax-highlighted within
text editor A text editor is a type of computer program that edits plain text. Such programs are sometimes known as "notepad" software (e.g. Windows Notepad). Text editors are provided with operating systems and software development packages, and can be us ...
s. These are sometimes referred to as "codetags" or "tokens". Such tags differ widely, but might include: * BUG, DEBUG — a known bug that should be corrected. * FIXME — should be corrected. * HACK, BODGE, KLUDGE — a workaround. * TODO — something to be done. * NOTE — used to highlight especially notable gotchas. * UNDONE — a reversal or "roll back" of previous code. * XXX — warn other programmers of problematic or misguiding code


Examples


Comparison

Typographic conventions to specify comments vary widely. Further, individual programming languages sometimes provide unique variants. For a detailed review, please consult the programming language comparison article.


Ada

The Ada programming language uses '--' to indicate a comment up to the end of the line. For example: -- 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;


APL

APL uses to indicate a comment up to the end of the line. 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

This section of
AppleScript AppleScript is a scripting language created by Apple Inc. that facilitates automated control over scriptable Mac applications. First introduced in System 7, it is currently included in all versions of macOS as part of a package of system autom ...
code shows the two styles of comments used in that language. (* This program displays a greeting. *) on greet(myGreeting) display dialog myGreeting & " world!" end greet -- Show the greeting greet("Hello")


BASIC

In this classic early
BASIC BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
code fragment the REM (''"Remark"'') keyword is used to add comments. 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
Microsoft Microsoft Corporation is an American multinational technology corporation producing computer software, consumer electronics, personal computers, and related services headquartered at the Microsoft Redmond campus located in Redmond, Washi ...
BASICs, 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 (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET * Visual Basic (c ...
,
Visual Basic .NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Vi ...
, and VB Script; and in descendants such as
FreeBASIC FreeBASIC is a free and open source multiplatform compiler and programming language based on BASIC licensed under the GNU GPL for Microsoft Windows, protected-mode MS-DOS ( DOS extender), Linux, FreeBSD and Xbox. The Xbox version is no longer ...
and
Gambas Gambas is the name of an object-oriented dialect of the BASIC programming language, as well as the integrated development environment that accompanies it. Designed to run on Linux and other Unix-like computer operating systems, its name is a ...
any text on a line after an ' (apostrophe) character is also treated as a comment. An example in Visual Basic .NET: Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' The following code is executed when the user ' clicks the button in the program's window. rem comments still exist. MessageBox.Show("Hello, World") 'Show a pop-up window with a greeting End Sub End Class


C

This C code fragment demonstrates the use of a prologue comment or "block comment" to describe the purpose of a conditional statement. The comment explains key terms and concepts, and includes a short signature by the programmer who authored the code. /* * 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 LIMIT_NPROCrlim_cur && !capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE)) goto bad_fork_free; Since C99, it has also been possible to use the // syntax from C++, indicating a single-line comment.


Cisco IOS and IOS-XE configuration

The
exclamation point The exclamation mark, , or exclamation point (American English), is a punctuation mark usually used after an interjection or exclamation to indicate strong feelings or to show emphasis. The exclamation mark often marks the end of a sentence, f ...
(!) 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 typic ...
(which contains the startup-config), nor are they displayed by the "show run" command. It is possible to insert
human-readable A human-readable medium or human-readable format is any encoding of data or information that can be naturally read by humans. In computing, ''human-readable'' data is often encoded as ASCII or Unicode text, rather than as binary data. In most c ...
content that is actually part of the configuration, and may be saved to the
NVRAM Non-volatile random-access memory (NVRAM) is random-access memory that retains data without applied power. This is in contrast to dynamic random-access memory (DRAM) and static random-access memory (SRAM), which both maintain data only for as lo ...
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 systems (AS) on the Internet. BGP is classified as a path-vector routing protocol, and it make ...
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


ColdFusion

ColdFusion uses comments similar to HTML comments, 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. Hello World


D

D uses C++-style comments, as well as nestable D-style multiline comments, which start with '/+' and end with '+/'. // This is a single-line comment. /* This is a multiline comment. */ /+ This is a /+ nested +/ comment +/


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. C C Lines that begin with 'C' (in the first or 'comment' column) are comments C WRITE (6,610) 610 FORMAT(12H HELLO WORLD) END 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. !* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * !* All characters after an exclamation mark are considered as comments * !* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * program comment_test print '(A)', 'Hello world' ! Fortran 90 introduced the option for inline comments. end program


Haskell

Line comments in Haskell start with '--' (two hyphens) until the end of line, and multiple line comments start with ''. -- 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". 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: 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 done in Haskell, using
LaTeX Latex is an emulsion (stable dispersion) of polymer microparticles in water. Latexes are found in nature, but synthetic latexes are common as well. In nature, latex is found as a milky fluid found in 10% of all flowering plants (angiosperm ...
. The code environment can be used instead of the Richard Bird's style: In
LaTeX Latex is an emulsion (stable dispersion) of polymer microparticles in water. Latexes are found in nature, but synthetic latexes are common as well. In nature, latex is found as a milky fluid found in 10% of all flowering plants (angiosperm ...
style this is equivalent to the above example, the code environment could be defined in the LaTeX preamble. Here is a simple definition: \usepackage \newenvironment later in % 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


Java

This
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
code fragment shows a block comment used to describe the setToolTipText method. The formatting is consistent with
Sun Microsystems Sun Microsystems, Inc. (Sun for short) was an American technology company that sold computers, computer components, software, and information technology services and created the Java programming language, the Solaris operating system, ZFS, t ...
Javadoc Javadoc (originally cased JavaDoc) is a documentation generator created by Sun Microsystems for the Java language (now owned by Oracle Corporation) for generating API documentation in HTML format from Java source code. The HTML format is used for ...
standards. The comment is designed to be read by the Javadoc processor. /** * 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)


JavaScript

JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, ofte ...
uses // to precede comments and /* */ for multi-line comments. // A single line JavaScript comment var iNum = 100; var iTwo = 2; // A comment at the end of line /* multi-line JavaScript comment */


Lua

The Lua programming language uses double-hyphens, --, for single line comments in a similar way to Ada,
Eiffel Eiffel may refer to: Places * Eiffel Peak, a summit in Alberta, Canada * Champ de Mars – Tour Eiffel station, Paris, France; a transit station Structures * Eiffel Tower, in Paris, France, designed by Gustave Eiffel * Eiffel Bridge, Ungheni, ...
,
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 has pioneered a number of programming lang ...
, SQL and
VHDL The VHSIC Hardware Description Language (VHDL) is a hardware description language (HDL) that can model the behavior and structure of digital systems at multiple levels of abstraction, ranging from the system level down to that of logic gat ...
languages. Lua also has block comments, which start with -- and run until a closing For example: -- A multi-line long comment print(20) -- print the result A common technique to comment out a piece of code, is to enclose the code between -- and --, as below: -- print(10) -- -- no action (commented out) In this case, it's possible to reactivate the code by adding a single hyphen to the first line: --- print(10) -- --> 10 In the first example, the -- 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 --- starts an ordinary, single-line comment, so that the first and the last lines become independent comments. In this case, the print is outside comments. In this case, the last line becomes an independent comment, as it starts with --. Long comments in Lua can be more complex than these, as you can read in the section called "Long strings" c.f. ''Programming in Lua''.


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, implementatio ...
'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 = [0 -1 0]; % seq = d .* (x - c).^n ./(factorial(n)) % We add-up to get the Taylor approximation approx = sum(seq)


Nim

Nim (programming language), Nim uses the '#' character for inline comments. 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 Markdown is a lightweight markup language for creating formatted text using a plain-text editor. John Gruber and Aaron Swartz created Markdown in 2004 as a markup language that is appealing to human readers in its source code form. Markdown i ...
and
ReStructuredText reStructuredText (RST, ReST, or reST) is a file format for textual data used primarily in the Python programming language community for technical documentation. It is part of the Docutils project of the Python Doc-SIG (Documentation Special Int ...
markups. The inline documentation comments use '##' and multi-line block documentation comments are opened with '## and closed with '#'. The compiler can generate
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript ...
,
LaTeX Latex is an emulsion (stable dispersion) of polymer microparticles in water. Latexes are found in nature, but synthetic latexes are common as well. In nature, latex is found as a milky fluid found in 10% of all flowering plants (angiosperm ...
and
JSON JSON (JavaScript Object Notation, pronounced ; also ) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other s ...
documentation from the documentation comments. Documentation comments are part of the
abstract syntax tree In computer science, an abstract syntax tree (AST), or just syntax tree, is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language. Each node of the tree denotes a construct occurring ...
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 uses nestable comments, which is useful when commenting a code block. codeLine(* comment level 1(*comment level 2*)*)


Pascal

In Niklaus Wirth's pascal family of languages (including Modula-2 and
Oberon Oberon () is a king of the fairies in 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, Queen of the Fairi ...
), comments are opened with '(*' and completed with '*)'. for example: (* test diagonals *) columnDifference := testColumn - column; if (row + columnDifference = testRow) or ....... In modern dialects of Pascal, '' are used instead.


Perl

Line comments in
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offi ...
, and many other
scripting language A scripting language or script language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. Scripting languages are usually interpreted at runtime rather than compiled. A scriptin ...
s, begin with a hash (#) symbol. # A simple example # my $s = "Wikipedia"; # Sets the variable s to "Wikipedia". print $s . "\n"; # Add a newline character after printing Instead of a regular block commenting construct, Perl uses Plain Old Documentation, a markup language for literate programming, for instance: =item Pod::List-Enew() Create a new list object. Properties may be specified through a hash reference like this: my $list = Pod::List->new(); See the individual methods/properties for details. =cut sub new


R

R only supports inline comments started by the hash (#) character. # This is a comment print("This is not a comment") # This is another comment


Raku

Raku (previously called Perl 6) uses the same line comments and POD Documentation comments as regular
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offi ...
(see Perl section above), but adds a configurable block comment type: "multi-line / embedded comments". These start with a hash character, followed by a backtick, and then some opening bracketing character, and end with the matching closing bracketing character. The content can not only span multiple lines, but can also be embedded inline. #` sub toggle-case(Str:D $s) #`( this version of parens is used now )


PHP

Comments in
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
can be either in C++ style (both inline and block), or use hashes. PHPDoc is a style adapted from Javadoc and is a common standard for documenting PHP code. 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 ': /** * This class contains a sample documentation. * * @author Unknown */ # ttributeclass MyAttribute


PowerShell

Comments in
Windows PowerShell PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sourc ...
# Single line comment Write-Host "Hello, World!" <# Multi Line Comment #> Write-Host "Goodbye, world!"


Python

Inline comments in Python use the hash (#) character, as in the two examples in this code: # This program prints "Hello World" to the screen print("Hello World!") # Note the new syntax Block comments, as defined in this article, do not technically exist in Python. A bare string literal represented by a triple-quoted string can be used,"Python tip: You can use multi-line strings as multi-line comments"
11 September 2011, Guido van Rossum
but is not ignored by the interpreter in the same way that "#" comment is. In the examples below, the triple double-quoted strings act in this way as comments, but are also treated as
docstring In programming, a docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, or even specifically formatted comments like docblocks, docst ...
s: """ 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"""


Ruby

Inline comments in
Ruby A 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 sap ...
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. 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"


SQL

Standard comments in SQL are in single-line-only form, using two dashes: -- 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 Alternatively, a comment format syntax identical to the "block comment" style used in the syntax for C and Java is supported by
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 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 relational database orga ...
,
SQLite SQLite (, ) is a database engine written in the C programming language. It is not a standalone app; rather, it is a library that software developers embed in their apps. As such, it belongs to the family of embedded databases. It is the mos ...
,
PostgreSQL PostgreSQL (, ), also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. It was originally named POSTGRES, referring to its origins as a successor to the Ingr ...
, and
Oracle An oracle is a person or agency considered to provide wise and insightful counsel or prophetic predictions, most notably including precognition of the future, inspired by deities. As such, it is a form of divination. Description The word '' ...
. MySQL also supports comments from the hash (#) character to the end of the line.


Swift

Single-line comments begin with two forward-slashes (//): // This is a comment. Multiline comments start with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/): /* This is also a comment but is written over multiple lines. */ Multiline comments in Swift can be nested inside other multiline comments. You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block: /* This is the start of the first multiline comment. /* This is the second, nested multiline comment. */ This is the end of the first multiline comment. */


XML (or HTML)

Comments in XML (or HTML) are introduced with For example, For compatibility with
SGML The Standard Generalized Markup Language (SGML; 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 two postulates": * Declarative: Markup should de ...
, the string "--" (double-hyphen) is not allowed inside comments.


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 interpre ...
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." A window of vulnerability (WOV) is a time frame within which defensive measures are diminished, com ...
.


See also

*
Docstring In programming, a docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, or even specifically formatted comments like docblocks, docst ...
, a specific type of comment that is parsed and retained throughout the runtime of the program. * Shebang, the use of ''#!'' as an interpreter directive in scripts on Unix-like systems * HTML comment tag * Literate programming, alternative documentation
paradigm In science and philosophy, a paradigm () is a distinct set of concepts or thought patterns, including theories, research methods, postulates, and standards for what constitute legitimate contributions to a field. Etymology ''Paradigm'' comes ...
* Syntax of comments in various programming languages * COMMENT (CONFIG.SYS directive) * REM (CONFIG.SYS directive)


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