Comment (computer programming)

From Hidden Wiki
Jump to navigation Jump to search

Template:Selfref

File:CodeCmmt002.svg
An illustration of Java source code with prologue comments indicated in red and inline comments in green. Program code is in blue.

In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters.[1][2] The syntax of comments in various programming languages varies considerably.

Comments are sometimes processed in various ways to generate documentation external to the source code itself by documentation generators, or used for integration with source code management systems and other kinds of external programming tools.

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).[3]

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) allow block comments to be recursively nested inside one another, but others (such as Java) do not.[4][5][6]

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.[6]

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.[6]

Uses

How best to make use of comments is subject to dispute; different commentators have offered varied and sometimes opposing viewpoints.[7][8] There are many different ways of writing comments and many commentators who offer sometimes conflicting advice.[8]

Planning and reviewing

Comments can be used as a form of pseudocode 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.

<source lang="cpp">/* loop backwards through all elements returned by the server (they should be processed chronologically)*/ for (i = (numElementsReturned - 1); i >= 0; i--){

   /* process each element's data */
   updatePattern(i, returnedElements[i]);

} </source>

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."[9]
"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."[10]

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: <source lang="vb">' 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") </source>

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.[11]

For example, a programmer may add a comment to explain why an insertion sort was chosen instead of a quicksort, as the former is, in theory, slower than the latter. This could be written as follows: <source lang="java">

list = [f (b), f (b), f (c), f (d), f (a), ...];
// Need a stable sort. Besides, the performance really does not matter.
insertion_sort (list);

</source>

Resource inclusion

Logos, diagrams, and flowcharts consisting of ASCII art constructions can be inserted into source code formatted as a comment.[12] Further, copyright 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 script contained in a Windows Script File running under Windows Script Host. 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.[13]

<source lang="xml"> <resource id="ProcessDiagram000"> <![CDATA[

HostApp (Main_process)
   |
   V

script.wsf (app_cmd) --> ClientApp (async_run, batch_process)

               |
               |
               V
        mru.ini (mru_history)  

]]> </resource> </source>

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.[13]

Metadata

Template:Main

Comments in a computer program often store metadata about a program file.

In particular, many software maintainers 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 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 or other reference.

Template:Anchor

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.

An example of commenting out code for exclusion purposes is below:

<source lang="C">

if (opt.equals ("e"))
  opt_enabled = true;
/*
if (opt.equals ("d"))
  opt_debug = true;
*/
if (opt.equals ("v"))
   opt_verbose = true;

</source> The above code fragment suggests that the programmer opted to disable the debugging option for some reason.

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

Template:Main Programming tools sometimes store documentation and metadata in comments.[14] These may include insert positions for automatic header file inclusion, commands to set the file's syntax highlighting mode,[15] or the file's revision number.[16] These functional control comments are also commonly referred to as annotations. 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.[17]

Examples of documentation generators include the programs Javadoc for use with Java, Ddoc for D, Doxygen for C, C++, Java, IDL, Visual Expert for PL/SQL, Transact-SQL, PowerBuilder and PHPDoc for PHP. Forms of docstring are supported by Python, Lisp, Elixir, and Clojure.[18]

C#, F# and Visual Basic implement a similar feature called "XML Comments" which are read by IntelliSense from the compiled .NET assembly.[19]

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 comments". Such "hot comments" may be the only practical solution that maintains backward-compatibility, but are widely regarded as a kludge.[20]

Stress relief

Sometimes comments in source code are used as a way to relieve stress by commenting about development tools, competitors, employers, working conditions, or the quality of the code itself.[21] The occurrence of this phenomenon can be easily seen from online resources that track profanity in source code.[22]

Normative views

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

Need for comments

Experts have varying viewpoints on whether, and when, comments are appropriate in source code.[9][25] 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.[9] Others suggest code should be extensively commented (it is not uncommon for over 50% of the non-whitespace characters in source code to be contained within comments).[26][27]

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.[28][29]

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:

   <source lang="java">
   String s = "Wikipedia"; /* Assigns the value "Wikipedia" to the variable s. */
   </source>

This level of detail, however, would not be appropriate in the context of production code, or other situations involving experienced developers. Such rudimentary descriptions are inconsistent with the guideline: "Good comments ... clarify intent."[10] Further, for professional coding environments, the level of detail is ordinarily well-defined to meet a specific performance requirement defined by business operations.[27]

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.[30]

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: <source lang="c"> /*

    This is the comment body.
    Variation One.
  • /

</source>

<source lang="c"> /***************************\

  • *
  • This is the comment body. *
  • Variation Two. *
  • *

\***************************/ </source>

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 editors that can automate the alignment and visual appearance of text in comments.

Software consultant and technology commentator Allen Holub[31] is one expert who advocates aligning the left edges of comments:[32]

<source lang="c">
/* This is the style recommended by Holub for C and C++.
 * It is demonstrated in Enough Rope, in rule 29.
 */
</source>
<source lang="c">
/* 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.
*/
</source>

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.[33]

Inline comment (End-of-line)

In this form, all the text from the ASCII characters // to the end of the line is ignored. <source lang="c"> // begin: Variation Three. // ------------------------- // This is the comment body. // ------------------------- </source>

Different styles can be chosen for different areas of code, from individual lines to paragraphs, routines, files, and programs. If the syntax supports both line comments and block comments, one method is to use line comments only for minor comments (declarations, blocks and edits) and to use block comments to describe higher-level abstractions (functions, classes, files and modules).

Sometimes projects try to enforce rules like "one comment every ten lines". These kinds of rules can be counterproductive when too rigorous, but may provide a useful standard of measurement and consistency if the project participants deem it necessary.

Inline comments using the characters Template:Code were part of the BCPL language. However, when Dennis Ritchie re-implemented BCPL as the B language, he chose to use PL/I's Template:Code block comments instead. This choice continued in the C language, Ritchie's successor to B.[34] Inline comments using Template:Code reappeared in C++ (itself a successor to C), which influenced their adoption in the 1999 standard of the C language.

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 grep utility or even syntax-highlighted within text editors. These are sometimes referred to as "codetags"[35][36] or "tokens".[37]

Such tags differ widely, but might include:

  • BUG – a known bug that should be corrected.
  • FIXME – should be corrected.
  • HACK – a workaround.
  • TODO – something to be done.
  • UNDONE – a reversal or "roll back" of previous code.
  • XXX – warn other programmers of problematic or misguiding code

Examples

Comparison

Template:Main

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: <source lang="ada">

 -- the air traffic controller task takes requests for takeoff and landing
  task type Controller (My_Runway: Runway_Access) is
     -- task entries for synchronous message passing
     entry Request_Takeoff (ID: in Airplane_ID; Takeoff: out Runway_Access);
     entry Request_Approach(ID: in Airplane_ID; Approach: out Runway_Access);
  end Controller;

</source>

AppleScript

This section of AppleScript code shows the two styles of comments used in that language. <source lang="AppleScript"> (* This program displays a greeting.

  • )

on greet(myGreeting)

    display dialog myGreeting & " world!"

end greet

-- Show the greeting greet("Hello") </source>

BASIC

This BASIC code fragment is a completely functioning program in which the REM ("REMark") keyword is used to add comments that describe what the program does. <source lang="qbasic"> 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 </source>

Any text on a line after an ' (apostrophe) character is also treated as a comment in Microsoft BASICs, including QuickBasic, QBasic, Visual Basic, Visual Basic .NET, and VBScript - and in descendants such as FreeBASIC and Gambas.

An example in Visual Basic .NET: <source lang="vbnet"> Public Class Form1

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       ' The following code is executed when the user
       ' clicks the button in the program's window.
       MessageBox.Show("Hello, World") 'Show a pop-up window with a greeting
   End Sub

End Class </source>

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. <source lang="c">

/*
 * Check if we are over our maximum process limit, but be sure to
 * exclude root. This is needed to make it possible for login and
 * friends to set the per-user process limit to something lower
 * than the amount of processes root is running. -- Rik
 */
if (atomic_read(&p->user->processes) >= p->rlim[RLIMIT_NPROC].rlim_cur
    && !capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE))
    goto bad_fork_free;

</source>

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 (!) may be used to mark comments in a Cisco router's configuration mode. Such comments are not, however, saved to non-volatile memory (which contains the startup-config), nor are they displayed by the "show run" command.[38][39]

By contrast, the following commands insert human-readable content that is actually part of the configuration, and may be saved to the NVRAM startup-config: The "description" command is used to add a description to the configuration of an interface or of a BGP neighbor, and the "name" parameter may be used to add a remark to a static route. Access lists may also contain "remarks."

<source lang="text"> ! 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 </source>

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.

<source lang="cfm">

<cfoutput>
  Hello World
</cfoutput>

</source>

Fortran IV

This Fortran IV code fragment demonstrates how comments are used in that language, which is very column-oriented. A letter "C" in column 1 causes the entire line to be treated as a comment.

<syntaxhighlight lang="fortranfixed"> C C Lines that begin with 'C' (in the first or 'comment' column) are comments C

     WRITE (6,610)
 610 FORMAT(12H HELLO WORLD)
     END

</syntaxhighlight>

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. <source lang="Fortran"> !* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * !* 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 </source>

Haskell

Line comments in Haskell start with '--' (two hyphens) until the end of line, and multiple line comments start with '{-' and end with '-}'. <source lang="Haskell"> {- this is a comment on more lines -} -- and this is a comment on one line putStrLn "Wikipedia" -- this is other comment </source>

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:

<source lang="lHaskell"> In Bird-style you have to leave a blank before the code.

> fact :: Integer -> Integer > fact 0 = 1 > fact (n+1) = (n+1) * fact n

And you have to leave a blank line after the code as well. </source> Literate programming can also be done in Haskell, using LaTeX. The code environment can be used instead of the Richard Bird's style: In LaTeX style this is equivalent to the above example, the code environment could be defined in the LaTeX preamble. Here is a simple definition: <source lang="lHaskell"> \usepackage{verbatim} \newenvironment{code}{\verbatim}{\endverbatim} </source> later in <source lang="lhaskell"> % the LaTeX source file The \verb|fact n| function call computes $n!$ if $n\ge 0$, here is a definition:\\ \begin{code} fact :: Integer -> Integer fact 0 = 1 fact (n+1) = (n+1) * fact n \end{code} Here more explanation using \LaTeX{} markup </source>

Java

This Java code fragment shows a block comment used to describe the setToolTipText method. The formatting is consistent with Sun Microsystems Javadoc standards. The comment is designed to be read by the Javadoc processor. <source lang="Java">

/**
 * This is a block comment in Java.
 * The setToolTipText method registers the text to display in a tool tip.
 * The text is displayed when the cursor lingers over the component.
 *
 * @param text  The string to be displayed.  If 'text' is null,
 *              the tool tip is turned off for this component.
 */
public void setToolTipText(String text) {
   //This is an inline comment in Java. TODO: Write code for this method.
}

</source>

JavaScript

JavaScript uses // to precede comments and /* */ for multi-line comments.

<source lang="JavaScript"> // A single line JavaScript comment var iNum = 100; var iTwo = 2; // A comment at the end of line /* multi-line JavaScript comment

  • /

</source>

Lua

The Lua programming language uses double-hyphens, --, for single line comments in a similar way to Ada, Eiffel, Haskell, SQL and VHDL languages. Lua also has block comments, which start with --[[ and run until a closing ]]

For example:

<source lang="Lua"> --[[A multi-line long comment ]] print(20) -- print the result </source>

A common technique to comment out a piece of code,[40] is to enclose the code between --[[ and --]], as below:

<source lang="Lua"> --[[ print(10) --]] -- no action (commented out) </source>

In this case, it's possible to reactivate the code by adding a single hyphen to the first line:

<source lang="Lua"> ---[[ print(10) --]] --> 10 </source>

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's programming language, the '%' character indicates a single-line comment. Multi line comments are also available via %{ and %} brackets and can be nested, e.g.

<source lang="matlab"> % These are the derivatives for each term d = [0 -1 0];

%{

 %{
   (Example of a nested comment, indentation is for cosmetics (and ignored).)
 %}
 We form the sequence, following the Taylor formula.
 Note that we're operating on a vector.

%} seq = d .* (x - c).^n ./(factorial(n))

% We add-up to get the Taylor approximation approx = sum(seq) </source>

OCaml

OCaml uses nestable comments, which is useful when commenting a code block. <source lang="ocaml"> codeLine(* comment level 1(*comment level 2*)*) </source>

Pascal

In Niklaus Wirth's pascal family of languages (including Modula-2 and Oberon), comments are opened with '(*' and completed with '*)'.

for example: <source lang="pascal"> (* test diagonals *) columnDifference := testColumn - column; if (row + columnDifference = testRow) or

   .......

</source>In modern dialects of Pascal, '{' and '}' are used instead.[41]

Perl

Line comments in Perl, and many other scripting languages, begin with a hash (#) symbol. <source lang="Perl">

  1. A simple example

my $s = "Wikipedia"; # Sets the variable s to "Wikipedia". print $s . "\n"; # Add a newline character after printing </source>

Instead of a regular block commenting construct, Perl uses Plain Old Documentation, a markup language for literate programming,[42] for instance:[43] <source lang="Perl"> =item Pod::List-E<gt>new()

Create a new list object. Properties may be specified through a hash reference like this:

 my $list = Pod::List->new({ -start => $., -indent => 4 });

See the individual methods/properties for details.

=cut

sub new {

   my $this = shift;
   my $class = ref($this) || $this;
   my %params = @_;
   my $self = {%params};
   bless $self, $class;
   $self->initialize();
   return $self;

} </source>

Perl 6

Perl 6 uses the same line comments and POD Documentation comments as regular Perl (see Perl section above), but adds a configurable block comment type: "multi-line / embedded comments".[44]

These start with a hash character, followed by a backtick, and then some opening bracketing character, and end with the matching closing bracketing character.[44] The content can not only span multiple lines, but can also be embedded inline. <source lang="perl6">

  1. `{{ "commenting out" this version

toggle-case(Str:D $s)

Toggles the case of each character in a string:

 my Str $toggled-string = toggle-case("mY NAME IS mICHAEL!");

}}

sub toggle-case(Str:D $s) #`( this version is used now ){

   ...

}


</source>

PHP

Comments in PHP 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.

PowerShell

Comments in Windows PowerShell

<source lang="powershell">

  1. Single line comment

Write-Host "Hello, World!"

<# Multi

  Line
  Comment #>

Write-Host "Goodbye, world!" </source>

Python

Comments in Python use the hash (#) character, as in the two examples in this code:

<source lang=python>

  1. This program prints "Hello World" to the screen

print("Hello World!") # Note the new syntax </source>

Specific block comments don't exist in Python, but a bare string literal represented by a triple-quoted string could be used.[45] In the examples below, the triple double-quoted strings act in this way as comments, but are also treated as docstrings:

<source lang="python"> """ Assuming this is file mymodule.py, then this string, being the first statement in the file, will become the "mymodule" module's docstring when the file is imported. """

class MyClass(object):

   """The class's docstring"""
   def my_method(self):
       """The method's docstring"""

def my_function():

   """The function's docstring"""

</source>

Ruby

Comments in Ruby.

Single line commenting: (line starts with hash "#") <source lang="Ruby"> puts "This is not a comment"

  1. this is commented

puts "This is not a comment" </source>

Multi-line commenting: (comments goes between keywords "begin" and "end") <source lang="Ruby"> puts "This is not a comment"

=begin

whatever goes in here

will be ignored

=end

puts "This is not a comment" </source>

SQL

Comments in SQL are in single-line-only form, when using two dashes: <source lang="SQL"> -- This is a single line comment -- followed by a second line SELECT COUNT(*)

      FROM Authors
      WHERE Authors.name = 'Smith'; -- Note: we only want 'smith'
                                    -- this comment appears after SQL code

</source> The syntax for Transact-SQL also supports alternative formats for specifying comments.[46] One format supported by this syntax is identical to the "block comment" style used in the syntax for C++ and Java.

Swift

Single-line comments begin with two forward-slashes (//):<syntaxhighlight lang="swift"> // This is a comment. </syntaxhighlight>Multiline comments start with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/):<syntaxhighlight lang="swift"> /* This is also a comment

but is written over multiple lines. */

</syntaxhighlight>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:<syntaxhighlight lang="swift"> /* 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. */

</syntaxhighlight>

XML

Comments in XML (or HTML) are introduced with <source lang="XML"></source>

For example,

<source lang="XML"> <param name="context" value="public"/> </source>

Security issues

In interpreted languages 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.[47]

See also

Notes and references

1 }}
     | references-column-width 
     | references-column-count references-column-count-{{#if:1|2}} }}
   | {{#if: 
     | references-column-width }} }}" style="{{#if: 2
   | {{#iferror: {{#ifexpr: 2 > 1 }}
     | Template:Column-width
     | Template:Column-count }}
   | {{#if: 
     | Template:Column-width }} }} list-style-type: {{#switch: 
   | upper-alpha
   | upper-roman
   | lower-alpha
   | lower-greek
   | lower-roman = {{{group}}}
   | #default = decimal}};">
  1. 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).Template:Cite book
  2. For purposes of this article, programming language comments are treated as indistinct from comments that appear in markup languages, configuration files and other similar contexts. Moreover, markup language is often closely integrated with programming language code, especially in the context of code generation. See e.g., Template:Cite book, Template:Cite book
  3. Template:Cite book
  4. Template:Cite book
  5. Template:Cite book
  6. 6.0 6.1 6.2 Template:Cite web
  7. Template:Cite book offers viewpoints on proper use of comments in source code. p. 66.
  8. 8.0 8.1 Template:Cite book discusses comments and the "Science of Documentation" p. 256.
  9. 9.0 9.1 9.2 The Elements of Programming Style, Kernighan & Plauger
  10. 10.0 10.1 Code Complete, McConnell
  11. Template:Cite book
  12. Template:Cite web
  13. 13.0 13.1 Template:Cite bookSometimes 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."
  14. See e.g., Template:Cite book page 243
  15. Template:Cite book describes the use of modeline syntax in Vim configuration files.
  16. See e.g., Template:Cite book page 168.
  17. Template:Cite book
  18. Function definition with docstring in Clojure
  19. Template:Cite book
  20. c2: HotComments
  21. "Microsoft Programmers Hid A Bunch Of Profanity In Early Software Code", Lisa Eadicicco, Mar 27, 2014, businessinsider.com.au
  22. (see e.g., Linux Swear Count).
  23. Template:Cite book, Template:Cite book
  24. See e.g., Template:Cite book page 65.
  25. Template:Cite web
  26. Template:Cite book
  27. 27.0 27.1 Template:Cite web 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."
  28. Template:Cite bookNon-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.
  29. Template:Cite book
  30. Template:Cite web
  31. Template:Cite web
  32. Allen Holub, Enough Rope to Shoot Yourself in the Foot, Template:ISBN, 1995, McGraw-Hill
  33. Template:Cite web
  34. Template:Cite web
  35. "PEP 0350 -- Codetags", Python Software Foundation
  36. "Never Forget Anything Before, After and While Coding", Using “codetag” comments as productive remainders
  37. "Using the Task List", msdn.microsoft.com
  38. Template:Cite web
  39. Template:Cite web
  40. Template:Cite web
  41. Template:Cite web
  42. Template:Cite web
  43. Template:Cite web
  44. 44.0 44.1 Template:Cite web
  45. "Python tip: You can use multi-line strings as multi-line comments", 11 Sep 2011, Guido van Rossum
  46. Template:Cite book
  47. Template:Cite book

Further reading

External links