Commenting Your Code


After you have worked out code that does some particular action, what happens when the code has to be modified 6 months later? You probably won’t remember what you were thinking or intending when you wrote the code, and you will have to spend significant time just trying to remember what you were trying to do. It is even worse if you have to modify someone else’s code. Well, never fear—there is an answer. C++ (as well as all other programming languages) provides a way for you to put comments in your code. A comment is simply an explanatory note that the compiler will ignore. Comments are for the programmer working on the code to read, not for the compiler. There are two ways to make a comment. The first is to put two forward slashes // at the beginning of that line, like you see in the following example.

// This variable is used to hold account numbers int account_num; 

The compiler will ignore the comment, but any programmer working on the code can read it to see what the code in question was meant to do. It is a common practice to put a few lines of comments at the beginning of a function, to explain the basic purpose of that function. Another way to make comments, if you have several lines of comment, is to enclose the comments with a beginning forward slash asterisk /* and end the comments with an asterisk forward slash */. Here is an example.

float square_number(float num) { /* This function takes in a single number then squares      that number  (multiplies it by itself) and returns the answer */  return num*num; }

Functions are simple. As such, some programmers skip comments all together. Your code will compile and run without comments. However, when you have to come back later and modify the code, you will be sorry if you did not comment it properly. I strongly encourage you to start early using comments in your code. Throughout the rest of this book you will frequently see comments used.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net