comment computer programming for comments in wikipedia markup see helpwiki markupcharacter formatting and wpcomment 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 programmerreadable 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 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 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 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 there are many different ways of writing comments and many commentators who offer sometimes conflicting advice 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 loop backwards through all elements returned by the server they should be processed chronologically for i numelementsreturned 1 i 0 i process each elements data updatepatterni returnedelements 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 its supposed to do code description comments can be used to summarize code or to explain the programmers intent according to this school of thought restating the code in plain english is considered superfluous the need to reexplain code may be a sign that it is too complex and should be rewritten or that the naming is bad dont document bad code rewrite it good comments dont repeat the code or explain it they clarify its intent comments should explain at a higher level of abstraction than the code what youre trying to do 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 servermappathlocal 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 functioncalls 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 list need a stable sort besides the performance really does not matter insertionsort list resource inclusion logos diagrams and flowcharts consisting of ascii art constructions can be inserted into source code formatted as a comment further copyright notices can be embedded within source code as comments binary data may also be encoded in comments through a process known as binarytotext 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 begin wsfresourcenodes resource idprocessdiagram000 cdata hostapp mainprocess v scriptwsf appcmd clientapp asyncrun batchprocess v mruini mruhistory resource 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 metadata 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 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 if optequals e optenabled true if optequals d optdebug true if optequals v optverbose true 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 uncomment and choose the appropriate option automatic documentation generation documentation generator programming tools sometimes store documentation and metadata in comments examples of documentation generators include the programs javadoc for use with java ddoc for d doxygen for c c java idl visual expert for plsql transactsql powerbuilder and phpdoc for php forms of docstring are supported by python lisp elixir and clojure c f and visual basic implement a similar feature called xml comments which are read by intellisense from the compiled net assembly syntax extension occasionally syntax elements that were originally intended to be comments are repurposed to convey additional information to a program such as conditional comments such hot comments may be the only practical solution that maintains backwardcompatibility but are widely regarded as a kludge 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 normative views there are various normative views and longstanding opinions regarding the proper use of comments in source code need for comments experts have varying viewpoints on whether and when comments are appropriate in source code 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 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 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 nonobstructive 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 editors that can automate the alignment and visual appearance of text in comments software consultant and technology commentator allen holub 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 holubs book in rule 31 the use of and as block comment delimiters was inherited from pli into the b programming language the immediate predecessor of the c programming language inline comment endofline in this form all the text from the ascii characters to the end of the line is ignored begin variation three this is the comment body 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 higherlevel 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 were part of the bcpl language however when dennis ritchie reimplemented bcpl as the b language he chose to use plis block comments instead this choice continued in the c language ritchies successor to b inline comments using 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 syntaxhighlighted within text editors these are sometimes referred to as codetags 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 comparison of programming languages syntax comments 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 myrunway runwayaccess is task entries for synchronous message passing entry requesttakeoff id in airplaneid takeoff out runwayaccess entry requestapproachid in airplaneid approach out runwayaccess end controller applescript this section of applescript code shows the two styles of comments used in that language this program displays a greeting on greetmygreeting display dialog mygreeting world end greet show the greeting greethello 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 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 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 public class form1 private sub button1clickbyval sender as systemobject byval e as systemeventargs handles button1click the following code is executed when the user clicks the button in the programs window messageboxshowhello world show a popup 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 peruser process limit to something lower than the amount of processes root is running rik if atomicreadpuserprocesses prlimrlimcur capablecapsysadmin capablecapsysresource goto badforkfree since c99 it has also been possible to use the syntax from c indicating a singleline comment cisco ios and iosxe configuration the exclamation point may be used to mark comments in a cisco routers configuration mode such comments are not however saved to nonvolatile memory which contains the startupconfig nor are they displayed by the show run command by contrast the following commands insert humanreadable content that is actually part of the configuration and may be saved to the nvram startupconfig 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 paste the text below to reroute traffic manually config t int gi02 no shut ip route 0000 0000 gi02 name isp2 no ip route 0000 0000 gi01 name isp1 int gi01 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 this prints hello world to the browser cfoutput hello worldbr cfoutput fortran iv this fortran iv code fragment demonstrates how comments are used in that language which is very columnoriented 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 6610 610 format12h 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 commenttest 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 end with this is a comment on more lines and this is a comment on one line putstrln wikipedia this is other 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 birdstyle you have to leave a blank before the code fact integer integer fact 0 1 fact n1 n1 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 the code environment can be used instead of the richard birds 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 usepackageverbatim newenvironmentcodeverbatimendverbatim later in the latex source file the verbfact n function call computes n if nge 0 here is a definition begincode fact integer integer fact 0 1 fact n1 n1 fact n endcode here more explanation using latex markup 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 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 settooltiptextstring text this is an inline comment in java todo write code for this method javascript javascript uses to precede comments and for multiline comments a single line javascript comment var inum 100 var itwo 2 a comment at the end of line multiline javascript comment lua the lua programming language uses doublehyphens for single line comments in a similar way to ada eiffel haskell sql and vhdl languages lua also has block comments which start with for example a multiline long comment print20 print the result a common technique to comment out a piece of code is to enclose the code between and as below print10 no action commented out in this case its possible to reactivate the code by adding a single hyphen to the first line print10 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 singleline 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 cf programming in lua matlab in matlabs programming language the character indicates a singleline comment multi line comments are also available via and brackets and can be nested eg these are the derivatives for each term d example of a nested comment indentation is for cosmetics and ignored we form the sequence following the taylor formula note that were operating on a vector seq d x cn factorialn we addup to get the taylor approximation approx sumseq ocaml ocaml uses nestable comments which is useful when commenting a code block codeline comment level 1comment level 2 pascal in niklaus wirths pascal family of languages including modula2 and oberon comments are opened with and completed with for example test diagonals columndifference testcolumn column if row columndifference testrow or in modern dialects of pascal and are used instead perl line comments in perl and many other scripting languages 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 item podlistegtnew create a new list object properties may be specified through a hash reference like this my list podlistnew start indent 4 see the individual methodsproperties for details cut sub new my this shift my class refthis this my params my self params bless self class selfinitialize return self 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 multiline 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 commenting out this version togglecasestrd s toggles the case of each character in a string my str toggledstring togglecasemy name is michael sub togglecasestrd s this version is used now 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 single line comment writehost hello world multi line comment writehost goodbye world python comments in python use the hash character as in the two examples in this code this program prints hello world to the screen printhello world note the new syntax specific block comments dont exist in python but a bare string literal represented by a triplequoted string could be used in the examples below the triple doublequoted strings act in this way as comments but are also treated as docstrings assuming this is file mymodulepy then this string being the first statement in the file will become the mymodule modules docstring when the file is imported class myclassobject the classs docstring def mymethodself the methods docstring def myfunction the functions docstring ruby comments in ruby single line commenting line starts with hash puts this is not a comment this is commented puts this is not a comment multiline commenting comments goes between keywords begin and end puts this is not a comment begin whatever goes in here will be ignored end puts this is not a comment sql comments in sql are in singlelineonly form when using two dashes this is a single line comment followed by a second line select count from authors where authorsname smith note we only want smith this comment appears after sql code the syntax for transactsql also supports alternative formats for specifying comments one format supported by this syntax is identical to the block comment style used in the syntax for c and java swift singleline comments begin with two forwardslashes this is a comment multiline comments start with a forwardslash followed by an asterisk and end with an asterisk followed by a forwardslash 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 comments in xml or html are introduced with and can spread over several lines until the terminator for example select the context here param namecontext valuepublic 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 docstring 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 unixlike systems html comment tag literate programming alternative documentation paradigm syntax of comments in various programming languages notes and references movshovitzattias dana and cohen william w 2013 natural language models for predicting programming comments in association for computational linguistics acl 2013 how to write comments by denis krukovsky source code documentation as a live user manual by ptlogica how to write comments for the javadoc tool doxygen a documentation system for c c java objectivec python idl and to some extent php c and d commentdriven development a personal presentation of good coding practice how to make comments the most important code you write by david njoku 