Search

1.2 — Comments

Types of comments

A comment is a line (or multiple lines) of text that are inserted into the source code to explain what the code is doing. In C++ there are two kinds of comments.

The // symbol begins a C++ single-line comment, which tells the compiler to ignore everything to the end of the line. For example:

Typically, the single line comment is used to make a quick comment about a single line of code.

Having comments to the right of a line can make both the code and the comment hard to read, particularly if the line is long. Consequently, the // comment is often placed above the line it is commenting.

The /* and */ pair of symbols denotes a C-style multi-line comment. Everything in between the symbols is ignored.

Since everything between the symbols is ignored, you will sometimes see programmers “beautify” their multiline comments:

Multi-line style comments do not nest. Consequently, the following will have unexpected results:

Rule: Never nest comments inside of other comments.

Proper use of comments

Typically, comments should be used for three things. For a given library, program, or function, comments are best 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 previously written) 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 a library, program, or function described above, comments can be used to describe how the code is going to accomplish its goal.

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 statement, not comment it.

Here are some examples of bad line comments and good statement comments.

Bad comment:

(yes, we already can see that sight is being set to 0 by looking at the statement)

Good comment:

(now we know WHY the player’s sight is being set to 0)

Bad comment:

(yes, we can see that this is a cost calculation, but why is items divided by 2?)

Good comment:

(now we know!)

Programmers often have to make a tough decision between solving a problem one way, or solving it another way. Comments are a great way to remind yourself (or tell somebody else) the reason you made one decision instead of another.

Good comments:

Finally, comments should be written in a way that makes sense to someone who has no idea what the code does. It is often the case that a programmer will say “It’s obvious what this does! There’s no way I’ll forget about this”. Guess what? It’s not obvious, and you will be amazed how quickly you forget. 🙂 You (or someone else) will thank you later for writing down the what, how, and why of your code in human language. Reading individual lines of code is easy. Understanding what goal they are meant to accomplish is not.

To summarize:

  • At the library, program, or function level, describe what
  • Inside the library, program, or function, describe how
  • At the statement level, describe why.

Commenting out code

Converting one or more lines of code into a comment is called commenting out your code. This provides a convenient way to (temporarily) exclude parts of your code from being included in your compiled program.

To comment out a single line of code, simply use the // style comment to turn a line of code into a comment temporarily:

Uncommented out:

Commented out:

To comment out a block of code, use // on multiple lines of code, or the /* */ style comment to turn the block of code into a comment temporarily.

Uncommented out:

Commented out:

or

There are quite a few reasons you might want to do this:

1) You’re working on a new piece of code that won’t compile yet, and you need to run the program. The compiler won’t let you run if there are compiler errors. Commenting out the code that won’t compile will allow the program to compile so you can run it. When you’re ready, you can uncomment the code, and continue working on it.

2) You’ve written code that compiles but doesn’t work correctly, and you don’t have time to fix it until later. Commenting out the broken code will ensure the broken code doesn’t execute and cause problems until you can fix it.

3) To find the source of an error. If a program isn’t producing the desired results (or is crashing), it can be useful in some cases to disable parts of your code to see if you can isolate what’s causing it to not work correctly. If you comment out one or more lines of code, and your program starts working as expected (or stops crashing), odds are whatever you last commented out was part of the problem. You can then investigate why those lines of code are causing the problem.

4) You want to replace one piece of code with another piece of code. Instead of just deleting the original code, you can comment it out and leave it there for reference until you’re sure your new code works properly. Once you are sure your new code is working, you can remove the old commented out code. If you can’t get your new code to work, you can always delete the new code and uncomment the old code to revert back to what you had before.

Commenting out code is a common thing to do while developing, so many IDEs provide support for commenting out a highlighted section of code. How you access this functionality varies by IDE (in Visual Studio, you can find it in the Edit menu under Edit->Advanced->Comment Selection/Uncomment Selection).

A note on comments in these tutorials

Throughout the rest of this tutorial series, I’ll be using comments inside code blocks to help illustrate how things work. Astute readers will note that by the above standards, most of these comments are horrible. 🙂 As you read through the rest of the tutorials, keep in mind that the comments are serving an intentional educational purpose, not trying to demonstrate what good comments look like.

1.3 -- A first look at variables, initialization, and assignment
Index
1.1 -- Structure of a program

73 comments to 1.2 — Comments

  • Very nice. Comments are always good to learn.

  • Julian

    I think of comments as a kind of “language translation” method. Imagine you are trying to learn another language such as French. As you are learning French, you are obviously not going to remember everything you learn after one look; there will be words that you will forget the meaning of etc unless of course you go over them many many times. Now imagine you’re only part way through learning French but you go to France for a holiday, forcing you to speak French in most places you visit. The ideal solution would be to take a French-English dictionary with you wherever you go. You can’t speak French fluently so you must use the French-English dictionary to help you understand different sentences in French. This is like using a C++-English dictionary to help you remember what sentences in C++ mean. Obviously, it would be very hard to eventually be able to speak C++ fluently, so the comments are kind of like C++ to English translations.

  • wastefuldragon

  • seb

    what do u mean by commenting out a code

    • drake

      what he means is that you add the “//” to the beginning of a line of code in order to turn it into a comment. This causes the compiler to ignore that line of code.

  • ImGoingToBePro

  • Nice explanation about comments.no comments on comments

  • A bad statement comment explains what the code is doing, you claim.

    That is true in many cases, but sometimes it can be very helpful to explain what code is doing.

    For example, when I learned PHP I had a hard time remembering the meaning of % (modulus) and added the explanation remainder of division every time I used modulus for a while until I know the explanation by heart.

    I think the best approach is to simply add all comments you find helpful.

  • hawk1821

    excellent reading for beginners

  • Helleri

    Ok. wait…I don’t get how I am supposed to use comments to not explain what something does but also make it clear what something does. I feel like I was told to do one thing and then told to do the opposite.

  • emerald820

    importance and correct usage of comments has been explained in an excellent way..thanks

  • Sergey

    Strange thing is that obvious rule to comment your code still needs a long discussion. “Bad comments” worse than “good comments”. But “no comments” is worst.

  • Sajid Ali Badsha Gilgiti

    🙂 programing is fun…. programing in c++ is really fun 🙂

  • Jim

    I would like to comment on the comment section… it was very good. I cannot comment on the comments of the commentators that posted comments for that would make this comment too long.

    • Alex

      We have enabled nested comments, so you can comment on the comments of the commentators that posted comments, should you wish. 🙂

      • Darren

        Just checking it was true that I could comment on the comment about being able to comment on the comments of the commentators that posted comments about commenting. I have too much time on my hands 🙁

  • Maria

    Hey! I don’t understand the commenting out the code???

    • Peverell

      This is your HelloWorld code:

      This is what he means by commenting out the code. I have commented out line 7:

      That is, if you don't immediately want a statement to be executed for whatever reason, adding // at the beginning of it i.e. commenting it out will enable your compiler to ignore it.

  • LIkith C

    My Comment

    Fantastic tutorial!!!

  • Dr.Chase

    This is really helpful stuff.
    I prefer learning this over the bjarne stroustrop book. He is like "Oh look I invented this it's so cool BTW I won't explain stuff well coz I'm too awesome for that". Jokin' :D.
    But this site makes things more comprehensable. Big LIKE!
    I'm a University student and I learn programming. The teacher actually doesn't teach anything.

  • Jeremy

    Microsoft recommends using the preprocessor to comment out code, since block comments cannot be nested (assuming there are already block comments in the code you’re trying to comment out).

    // 0 is always ‘false’ so the code between #if 0 and #endif will not be compiled:
    #if 0

    /*
    ** Assume this is a bunch of code
    ** that you wish to comment out.
    */

    #endif

    • Alex

      That will work, but the downside is that your IDE won’t color code it as a comment for you. That can lead to errors, as it makes it much harder to tell what code is “live” vs not.

      Personally, I like to use // for normal comments, and /* */ for commented out code. I just have to make sure I don’t comment out the same block of code more than once.

      Fortunately, if you do try to nest C-style comments, it usually causes compiler errors because the compiler doesn’t know what to do with your uncommented comment text.

  • subhranshu

    thanks a lot
    very well structured tutorial

  • Kees van de Wetering

    This is great stuff, thanks.

  • Olaf

    This is beyond power ><

  • Niranjan.A.S

    Great tutorial

  • Warlaan

    Overall a great tutorial, but as a senior programmer I disagree with the first example for a bad comment.

    Imho that’s a good comment, because comments aren’t as much about explaining the code or providing orientation as they are about explaining your intention. If you look at this code for example:

    It’s still very obvious what the code does - unfortunately it’s also not what was intended. With both the code and the comment easy to read it is now very easy to spot the bug.

    A comment like

    describes a higher level of code, e.g.:

  • Raman Kamat

    U R AWSMMMMMMM ALEX..
    ENJOYING THIS TUTORIAL 🙂
    FABULOUS WORK 🙂 🙂

  • Mohammad Abolnejadian

    in xcode it says to make endl; to std::endl

  • dartagnan

    thanks for all the hard work,really appreciate it

  • Mato

    Hi Alex,
    Please could you tell about:
    //(* *)// and
    \
    kind of comments.
    Thank you,

    • Alex

      //(* *)// is just a // style comment with other symbols added in for fanciness.
      \ is not a comment at all. I don’t know what this is meant to be.

  • Gabor

    Hi Alex!

    At the part "Multi-line style comments do not nest." Would not be it better to write

    (Comment ends at the /, not at the preceding *.)
    Thanks for the tutorial!

  • Aiden

    i tried to do

    it worked, but it didnt do anything? im wondering if its supposed to and im doing something wrong

    • Alex

      You mean it compiled but didn’t produce any output? Did you actually run the program you created? If so, it’s possible the output flashed on the screen and then disappeared when the program terminated. Lesson 0.7 contains some advice on how to address that issue.

  • Thanks for the explanation 🙂

  • OmarAlMadani

    Loved the last advice of the lesson. Pleasant and brilliant work, thanks.

  • Mohammed Khalil Ait Brahim

    I found a typo in this sentence : "Having comments to the right of a line can make <b>the both</b> the code and the comment hard to read, particularly if the line is long. Consequently, the // comment is often placed above the line it is commenting."

    I think that it should be "both" rather than "the both"

  • Mohsin

    Why do we comment out code when we can just erase it?

    • Alex

      Sometimes we just want to disable it temporarily, to see what will happen if it doesn’t execute.

      Alternatively, if we’re replacing one bit of code with another, it can be useful to comment out the original code so you have a reference while you write the new code.

      Generally, you won’t want to leave lots of commented out code sitting around long term.

  • Eoku

    When I was learning Python in school, I had a friend who always asked me to help him when his code wasn’t working. He always expected me to know what his code meant and if I didn’t he would get frustrated with me. I might have to send him this. I guess, though, most of his problems were because he WASN’T INDENTING HIS GOD DAMN CODE PROPERLY IF AT ALL. That’s a way worse offense than simply never commenting.

    • Alex

      Yes, that’s the worst. Fortunately most IDEs can auto-format code for you. Just paste it in, select the autoformat command, and they’ll fix all the indentation issues.

  • Mehdi

    // This toturial is about learning commenting code.

    // Before each code line bescribe what you are doing.

    // The reason we are commenting is to explain what the code is doing.

  • Daniel

    The "endl" element is C++ for "end line" in english correct?

  • Elpidius

    Hey Alex,

    What’s the difference between "at the program, library or function level" and "within the program, library or function level"?

    Would ‘at the program level’ be written above main() ?
    e.g.

    Would ‘within the program level’ be written after main() ?
    e.g.

    Or is ‘at’ and ‘within’ in the same place? Please explain this?

    Thanks in advance.

  • Vidya Moger

    I never new so much about comments. Till date I have always used bad comments. I will consider your valuable points here after….

  • Guy

    Just an FYI to the creators, there’s a typo.
    "Finally, comment should be written in a way" should read
    "Finally, comments should be written in a way".

  • Aaron

    This page was super interesting/helpful/straightforward/simple to understand. Nice for a noob like me ;D Thanks @Alex!

  • liviu balas

    Thank you! 🙂

  • Danny

    Insert recycled pun about a comment commenting on a comment on a c++ tutorial chapter called "comments."

  • shahadat husain

    comment //
    programme is very must usefull

  • Chan3x

    Hello

    or just like this

  • Mr Alex,
    Please let me again express my sincere gratitude for your helpful website. And a comment: although in your reply by June 24, 2015 at 9:18 am, to Mr Mohammad Abolnejadian, you state that have "updated the example so that both cout and endl are qualified with std::", in the first example, "endl" is not preceded by "std::". I think either is correct. "endl" be preceded by "std::" or "using namespace std;" be including in header, and "std::" be deleted before "cout" as superfluous.
    With regards and friendship.

    • Alex

      I’ve updated the first endl so it is also preceded by std::.

      While you can use namespace std to be able to omit the prefixes, I only recommend doing so judiciously (and not in the global namespace as most people who use that seem to do).

  • Matt

    Typo before your last "good comments" example. You wrote:
    "Comments are a great way to remind yourself (or tell somebody else) the reason you made a one decision instead of another."

    I think the second "a" should be removed.

  • Robert

    What is the difference between "at the function level" and "inside the function"?, can someone give an example? I mean, when writing a new function, where exactly should I describe "what" it does and where "how" does it do it? thx

    • Alex

      By “function level” I mean a comment that describes what the entire function does. By “inside the function”, I mean a comment that describes how the code that follows works.

      A typical function will look like this:

  • GEScott71

    My understanding of the key points in this lesson:
    - Comment at the library, program, function level to describe WHAT it does
    - Comment inside the library, program, or function level to describe HOW it does it
    - Comment at the statement level to describe WHY it does it

    Use // to comment individual lines; best used for comments
    Use /* and */ to comment out sections of code

    Thanks Alex!

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter