Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Comments

Part of TutorialFundamentals

Description

Good documentation is a good idea.

Types of Comments in D

There are three types of comments in D:

  1. Line comments: //
  2. Block comments: /* */
  3. Nested comments: /+ +/

Line Comments

Line comments begin with // and continue until the end of the line. The comment automatically ends at the end of the line, so make sure the next line is valid code. If you want a multiple-line comment, then use a block comment or a nested comment. (If your code gets word-wrapped, your code would break, but you probably should try avoiding editors that word-wrap your code anyways.)

If you're familiar with modern flavors of BASIC, // is equivalent to a ' or REM.

Block Comments

Block comments can exist entirely a line or contain multiple lines of commentary. Block comments begin with a /* and end with a */. If you forget a matching closing symbol, your code will either do something you didn't expect, or it won't compile at all. Block comments don't nest. If you want nesting comments, then use nested comments.

Nested Comments

Nested comments can exist entirely a line or contain multiple lines of commentary. Nested comments begin with a /+ and end with a +/. Just like block comments, openning comment markers must be matched with closing marks.

These comments do nest so that you can put one inside another. The most obvious use for this feature is to "comment out" code that you don't want to compile right now (because you're not sure if it's any good) but might be valuable code. Of course, once you decide it's garbage, you'd want to delete the whole passage. Nested comments are a little more complicated than single-line or block comments, so they aren't used in the in this fairly simple example included below.

Example

/* 
This program demonstrates using comments in D.
(Such as the multi-line comment this sentence resides in.)
*/

import std.stdio; // This is the module that allows us to use writef later...

/*   
  This is another block (or multiline) comment.  
*/

int main() {
  /* The main function is where the action starts in D. */
    
  writefln("This program is documented."); // This statement prints some text...
        
  // This is a single line comment.  It automatically ends at the end of the line.

  return /* 0 is an int */ 0;

  /* 
    since main is supposed to return an int ("integer"), 
    the above statement is required... 
  */ 
}