Show: Delphi C++
Display Preferences

Comments

From RAD Studio
Jump to: navigation, search

Go Up to Whitespace Overview Index

Comments are pieces of text used to annotate a program. Comments are for the programmer's use only; they are stripped from the source text before parsing.

There are two ways to delineate comments: the C method and the C++ method. The compiler supports both methods, and provides an additional, optional extension permitting nested comments. If you are not compiling for ANSI compatibility, you can use any of these kinds of comments in both C and C++ programs.

You should also follow the guidelines on the use of whitespace and delimiters in comments discussed later in this topic to avoid other portability problems.

C comments

A C comment is any sequence of characters placed after the symbol pair /*. The comment terminates at the first occurrence of the pair */ following the initial /*. The entire sequence, including the four comment-delimiter symbols, is replaced by one space after macro expansion. Note that some C implementations remove comments without space replacements.

The compiler does not support the nonportable token pasting strategy using /**/. Token pasting is performed with the ANSI-specified pair ##, as follows:

#define VAR(i,j)  (i/**/j)    /* won't work */
#define VAR(i,j)  (i##j)      /* OK */
#define VAR(i,j)  (i ## j)    /* Also OK */

The compiler parses the declaration,

int /* declaration */ i /* counter */;

as these three tokens:

int   i;

See Token Pasting with ## for a description of token pasting.

C++ comments

C++ allows a single-line comment using two adjacent slashes (//). The comment can start in any position, and extends until the next new line:

class X {  // this is a comment
... };

You can also use // to create comments in C code. This feature is specific to the C++Builder compiler and is generally not portable.

Nested comments

ANSI C doesn't allow nested comments. The attempt to comment out a line

/*  int /* declaration */ i /* counter */; */

fails, because the scope of the first /* ends at the first */. This gives

i ; */

which would generate a syntax error.

To allow nested comments, check Project|Options|Advanced Compiler|Source|Nested Comments.

Delimiters and whitespace

In rare cases, some whitespace before /* and //, and after */, although not syntactically mandatory, can avoid portability problems. For example, this C++ code:

int i = j//* divide by k*/k;
+m;

parses as int i = j +m; not as

int i = j/k;
+m;

as expected under the C convention. The more legible

int i = j/ /* divide by k*/ k;
+m;

avoids this problem.

See Also

Personal tools
RAD Studio 10.2 Tokyo
In other languages
Previous Versions
Assistance