Thursday, July 15, 2010

C++: Important: COMMENT YOUR CODE!!!

Once, a beginning programming student handed in his first programming
assignment - a program that'll calculate average of three numbers. The
student thought to himself, "maybe I'll get an A+ thanks to the speed in
which I've wrote my program." In the next lecture, he was shocked to find
that he got a solid "B" on his programming exercise. Furious at his grades,
he decided to visit his professor during her next office hours.
Thus the conversation went...
Student: I thought I'd get A+ on this assignment! It took me only ten
minutes to write everything!
Professor: I appreciate the speed in which you compose this wonderful
program. But have you checked out the forum posts that I've made about
something that I went over during the first lecture?
Student: Er... I might have - I might have forgot.
Professor: I see. Why don't you look at the back of your paper and tell me
what I wrote to you...
Student (reading the back of his assignment paper and his face falls): I
see. "I could've given you an A+ if you've took some time to comment your
code and told me what you were doing exactly."
Professor: Yes, commenting always helps when you are programming. Try
commenting your code - maybe I'll give you a better grade next time.

Yes, I tell you, commenting has saved my life multiple times. It is a best
practice to know what you are doing, and one way to "keep your program in
progress" is commenting your code. From my experiences, commenting helped me
know exactly what data to use, as well as helped my professor give me
suggestions based on my comments and code.

There are two ways to comment a code: a "one liner" and multiple line
version. A one liner is useful if you want to write a small comment on a
single line, and it is identified by the two slashes (//) in front of your
comment. Anything on the line after this operator will be marked as a
comment. For example:
string school_name; // The name of my school.
Means that the text after the // (in this case, a short description of the
string variable) will be marked as a comment.

As opposed to this, the "multiple line version" allows one to mark multiple
lines as a comment section. To do that, you would surround the comment
section with /* (slash and a star) and */ (star and slash), like this:
/* Beginning of my comments. Note that if you don't end a comment by putting
a star-slash(*/), you might get a situation where your code would be treated
as a comment! So, if you find that something is not working after you wrote
your multiple line comment, check to see if you've ended your comment
section.
End of my comments. */

With that in mind, let's continue with our programming adventure...
// JL

No comments:

Post a Comment