Typically, comments should be used for three things. At the library, program, or function level, comments should be used to describe what the library, program, or function, does. For example:
All of these comments give the reader a good idea of what the program is trying to accomplish without having to look at the actual code. The user (possibly someone else, or you if you’re trying to reuse code you’ve already written in the future) can tell at a glance whether the code is relevant to what he or she is trying to accomplish. This is particularly important when working as part of a team, where not everybody will be familiar with all of the code.
Second, within the library, program, or function described above, comments should be used to describe how the code is going to accomplish it’s goal.
/* To calculate the final grade, we sum all the weighted midterm and homework scores and then divide by the number of scores to assign a percentage. This percentage is used to calculate a letter grade. */
Typically, comments should be used for three things. At the library, program, or function level, comments should be used to describe what the library, program, or function, does. For example:
// To generate a random item, we're going to do the following:
// 1) Put all of the items of the desired rarity on a list
// 2) Calculate a probability for each item based on level and weight factor
// 3) Choose a random number
// 4) Figure out which item that random number corresponds to
// 5) Return the appropriate item
These comments give the user an idea of how the code is going to accomplish it’s goal without going into too much detail. At the statement level, comments should be used to describe why the code is doing something. A bad statement comment explains what the code is doing. If you ever write code that is so complex that needs a comment to explain what a statement is doing, you probably need to rewrite your code, not comment it.