Search

1.2 — Comments

A comment is a programmer-readable note that is inserted directly into the source code of the program. Comments are ignored by the compiler and are for the programmer’s use only.

In C++ there are two different styles of comments, both of which serve the same purpose: to help programmers document the code in some way.

Single-line comments

The // symbol begins a C++ single-line comment, which tells the compiler to ignore everything from the // symbol 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. If the lines are fairly short, the comments can simply be aligned (usually to a tab stop), like so:

However, if the lines are long, placing comments to the right can make your lines really long. In that case, single-line comments are often placed above the line it is commenting:

Author's note

The statements above represent our first encounters with snippets of code. Because snippets aren’t full programs, they aren’t able to be compiled by themselves. Rather, they exist to demonstrate specific concepts in a concise manner.

If you would like to compile a snippet, you’ll need to turn it into a full program in order for it to compile. Typically, that program will look something like this:

Multi-line comments

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 multi-line comments:

Multi-line style comments can not be nested. Consequently, the following will have unexpected results:

When the compiler tries to compile this, it will ignore everything from the first /* to the first */. Since this is not inside the comment */ is not considered part of the comment, the compiler will try to compile it. That will inevitably result in a compile error.

This is one place where using a syntax highlighter can be really useful, as the different coloring for comment should make clear what’s considered part of the comment vs not.

Warning

Don’t use multi-line comments inside other multi-line comments. Wrapping single-line comments inside a multi-line comment is okay.

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. These are typically placed at the top of the file or library, or immediately preceding the function. For example:

All of these comments give the reader a good idea of what the library, program, or function 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 its goal without having to understand what each individual line of code does.

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:

Reason: We already can see that sight is being set to 0 by looking at the statement

Good comment:

Reason: Now we know why the player’s sight is being set to 0

Bad comment:

Reason: We can see that this is a cost calculation, but why is quantity multiplied by 2?

Good comment:

Reason: Now we know why this formula makes sense.

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.

Best practice

Comment your code liberally, and write your comments as if speaking to someone who has no idea what the code does. Don’t assume you’ll remember why you made specific choices.

Author's note

Throughout the rest of this tutorial series, we’ll use comments inside code blocks to draw your attention to specific things, or help illustrate how things work (while ensuring the programs still compile). 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.

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 new 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 sometimes be useful 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.

For Visual Studio users

You can comment or uncomment a selection via Edit menu > Advanced > Comment Selection (or Uncomment Selection).

For Code::Blocks users

You can comment or uncomment a selection via Edit menu > Comment (or Uncomment, or Toggle comment, or any of the other comment tools).

Tip

If you always use single line comments for your normal comments, then you can always use multi-line comments to comment out your code without conflict. If you use multi-line comments to document your code, then commenting-out code using comments can become more challenging.

If you do need to comment out a code block that contains multi-line comments, you can also consider using the #if 0 preprocessor directive, which we discuss in lesson 2.10 -- Introduction to the preprocessor.

Summary

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

1.3 -- Introduction to variables
Index
1.1 -- Statements and the structure of a program

130 comments to 1.2 — Comments

  • brunda

    what is the necessity of <<std::endl

  • Sin

    I can use // lkjsadlkjasdlkasjdkjasdlkjaklds // rather than a dot , right ?>

  • KENTOT

    What are the types of comments?

  • Rrr

    std:cout<<x vs std:cout<<"x"
    Giving output of x when it is variable

    #include<iostream>

    int main()
    {
    Int x=5;
    Std cout<<x;
    return 0;
    }

  • Rrr

    When I use quotation"  "for a sentence after std::cout it works fine and gives the output, but when defining x as variable and after assigning a constant value to it,it doesn't give output with quotation,only without it.. why???

  • eugene

    wwhy dont you guys use code blocks during the lessons

  • Ayush kulkarni

    Hey bro(ALEX), you are the best tutor ever.You really give out what you have.It is the best experience to learn with you.Keep it up! you really screwd all the other tutorials!....

  • My dear c++ Teacher,
    Please let me this question:
    Before last sentence and somewhere else, there is a square with "0IF642" or "01F642" inside. What does it mean?
    With regards and friendship.

    • Alex

      It looks like WordPress is converting my smiley into an emoji, which is being represented as a unicode character. Your browser apparently doesn't know how to interpret this.

      That said, I'd previously disabled emojis on this site, and apparently that is no longer the case. I'll have to investigate why.

  • My dear c++ Teacher,
    Please let me say, I do not understand following:
    "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.".
    Do you mean "if did not coment it"?.
    With regards and friendship.

    • Alex

      No. I am trying to say that if you need to write a comment to explain what code is doing, then your code is probably too complex. You should simplify your code.

  • Alice

    I couldn't find "Edit->Advanced->Comment Selection/Uncomment Selection".
    What does it do anyway? What kind of "support" will the MVS provide?
    I was looking for it in order to make the comments visible.

    • Alex

      That command only exists in Visual Studio, so if you're using some other IDE it won't be there. All it does is add line comments (// style) in front of each line of a block of code, or remove them.

  • Rifatul

    Is it me only that I did not able to understand! :(

  • 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!

  • 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:

  • 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.

  • 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.

  • Chan3x

    Hello

    or just like this

  • shahadat husain

    comment //
    programme is very must usefull

  • Danny

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

  • liviu balas

    Thank you! :)

  • Aaron

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

  • 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".

  • 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....

  • 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.

  • Daniel

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

  • 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.

  • 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.

  • 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.

  • 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"

  • OmarAlMadani

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

  • Thanks for the explanation :)

Leave a Comment

Put all code inside code tags: [code]your code here[/code]