Comment (computer programming)


In computer programming, a comment is text embedded in source code that a translator ignores. Generally, a comment is an annotation intended to make the code easier for a programmer to understand often explaining an aspect that is not readily apparent in the program code. For this article, comment refers to the same concept in a programming language, markup language, configuration file and any similar context. Some development tools, other than a source code translator, do parse comments to provide capabilities such as API document generation, static analysis, and version control 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 guide. But, best practices are disputed and contradictory.

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 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 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 it refers. Both prologue and inline comments can be represented as either line or block comments. For example:

/*
* prologue block comment
*/
bool foo
//
// prologue line comment
//
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.

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

The example below explains why an insertion sort was chosen instead of a quicksort, as the former is, in theory, slower than the latter.

list = ;
// Need a stable sort. Besides, the performance really does not matter.
insertion_sort ;

Describe algorithm

Comments can describe an algorithm as pseudocode. This could be done before writing the code as a first draft. If left in the code, it can simplify code review by allowing comparison of the resulting code with the intended logic. For example:
/* loop backwards through all elements returned by the server
  • /
for

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.

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 actions such as a keyboard shortcut.

Store metadata

Comments can store metadata about the code. Common metadata includes the name of the original author and subsequent maintainers, dates when first written and modified, link to development and user documentation, and legal information such as copyright and software license. Rarely, text-encoded. binary data can be included.
Some programming tools write metadata into the code as comments. For example, a version control 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 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 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, Ddoc, Doxygen, Visual Expert and PHPDoc. Forms of docstring are supported by Python, Lisp, Elixir, and Clojure. C#, F# and Visual Basic.NET implement a similar feature called "XML Comments" which are read by IntelliSense from the compiled.NET assembly.

Visualization

An ASCII art visualization such as a logo, diagram, or flowchart can be included in a comment.
The following code fragment depicts the process flow of a system administration script. Although a section marking the code appears as a comment, the diagram is in an XML CDATA section, which is technically not a comment, but serves the same purpose here. 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.


HostApp
|
V
script.wsf --> ClientApp
|
|
V
mru.ini
>

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.
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:

  1. !/usr/bin/env python3
  2. -*- coding: UTF-8 -*-
print

The gcc compiler looks for a comment in a switch statement if a case falls-thru to the next case. If an explicit indication of fall-thru is not found, then the compiler issues a warning about a possible coding problem. Inserting such a comment about fall-thru is a long standing convention, and the compiler has codified the practice. For example:

switch

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.

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.
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.
Comments are sometimes used to document contracts in the design by contract approach to programming.