Lesson 12 | Comment style |
Objective | Examine the preferred comment style in C++. |
C++ Preferred Comment Style
C ++ Examples
Here are two examples of using the rest-of-line comment symbol:
// C++: GCD program
const int N = 200; //N is the number of trials
The bracket-pair comment symbols are still useful, especially for lengthy, multi-line comments:
/* * * * * * * * * * * * * * *
Programmer: Alan Turing
Compiler: Borland 5.0
Modifications: 10-2-2022 cplusoop.com
* * * * * * * * * * * * * * */
Comments versus Self-commenting Code
Function Comments
/**
Computes the value of an investment with compound interest.
@param initial_balance the initial value of the investment
@param p the interest rate per period in percent
@param n the number of periods the investment is held
@return the balance after n periods
*/
double future_value(double initial_balance, double p, int n){
double b = initial_balance * pow(1 + p / 100, n);
return b;
}
Discussion of Function Comments
The function comment does not document the implementation but the idea which is a more valuable property.
According to the documentation style used in this course, every function (except main) must have a comment.
The first part of the comment is a brief explanation of the function. Then supply an @param entry for each parameter, and an @return entry to describe the return value.
As you will see later, some functions have no parameters or return values.
For those functions, @param or @return can be omitted.
This particular documentation style is borrowed from the Java programming language and is called the javadoc style.
There are a number of tools available that process C++ files and extract HTML pages containing a hyperlinked set of comments.
When comments are not necessary
Occasionally, you will find that the documentation comments are unnecessary to write. That is particularly true for general-purpose functions:
/**
Computes the maximum of two integers.
@param x an integer
@param y another integer
@return the larger of the two inputs
*/
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
Adding Comments - exercise