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

131 comments to 1.2 — Comments

  • Jonas

    Found a typo under 'Proper use of comments'. The first comment should say (asterisks mark the erroneous word):
        
    // This program *calculates* the student's final grade based on his test and homework scores.

  • skibi

    I don't really understand this concept at all

  • Dear Teacher,

    Please let me say you that following program works in Visual Studio 2017, 2019, and online compilers
    http://cpp.sh/
    https://www.onlinegdb.com/online_c++_compiler

    Regards

    • Behavior is undefined. Make sure you followed lesson 0.10 and 0.11.

      • Mr. nascardriver,

        Please accept my many thanks for you responded to my message and that immediately. Many more for your message is instructive.
        I appreciate that "behavior is undefined".
        However after I have configured V.S. 2017 and 2019 according to lessons 0.10 and 0.11 (setting "Disable Language Extensions" to Yes (/Za), and "Warning level" to Level4 (/W4)) warnings are many.
        In V.S. 2017 of the kind
        "'Project5.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file."
        and in V.S. 2019 RC of the kind
        "'Project-comment.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'."
        Only name in .dll file is different in warnings.

        With regards and friendship
        Georges Theodosiou

    • Badreddine Boukheit

      # include <iostream> Everything from here to the end of the line is ignored

      there is an error in this line sir , you should put // before the things that you do not want the compiler to compile , the line should be :

      # include <iostream> //Everything from here to the end of the line is ignored

    • Todd Riemenschneider

      Thanks for the tip Georges!

      • Mr. Todd Riemenschneider
        Please let me express my thanks for your comment and many more for your thanks. Also let me a greater tip: Undefined behavior is the greatest problem I face in learning programming. Regards.

  • Bastian

    if you have a bit of code that you will frequently comment out and put back in, you can just put /**/ below the code you want commented out, then when you need it commented out, you can just place /* above the code, like

  • Mr.F

    Hey Alex.
    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. But won't that result in a compile error if I exclude one line of the code?

    • Alex

      Only if you comment out a declaration and not the use of it later.

      If you're strategic about what you comment out, you can avoid this. The easiest thing to comment out are function calls that don't use a returned value. You can try commenting out parts of functions, or even entire functions as long as you comment out all the calls to those functions too.

  • Tom

    Thanks for sharing this post,
    is very helpful article.

  • Louis Cloete

    Hey Alex!

    I must say, I like this new styling of the pages a lot! Just a comment (no pun intended) about multiline comments to disable code: If you want to disable code and you are not sure if it contains multiline comments, you can do this:

    Then you don't have to worry about multiline comments inside the block you want to disable.

  • Smidge

    Thanks again for this wonderful tutorial, however you missed a single semi-colon on one of your examples.

  • Ajay Shinde

    did i use comments properly?

    • Felipe

      I think that a comment if for you and other people is understandable what you want to comment, it is valid, for me this is valid and, it is a good way to comment. Good luck in this bro!

      PD: Remember put
      before '}', put 'return 0;'
      And if you wan't to pause the program put on first line '#include <conio.h>' and before of return 0; ,
      'getche();', or if you have an error put  '_getche();'

  • Henric

    Hi Alex!
    These are some amazing tutorials and I think it's great that you still are improving it after a long time!

    There seems to be a typo in the "Proper use of comments" section. The first comment says "This program calculate the student's final grade..." rather than "...calculateS the student's final grade..."

  • Allu orton

    Big thanks Alex

  • boredprogrammer

    For uncommenting code blocks using common comment syntax is not a good idea.

    /*
      a = TEST;
      cout << a;
    */

    In general, it's not a good idea. Why? we tend to do that for different reasons but mostly to test some code or keep some code for later testing. The problem is, it's easy to forget those pieces of code with many comments around. Or popullate your code with commented code that other programer could see and think "what is that? is commented because it's not used anymore? or a piece of code pending of testing? or the developer forgot to uncomment a vital piece of code?".

    This is the main problem, and worst, it also happened to me with my own code, when time later I found commented code and I wasn't sure why it was commented (of course I didn't leave any message).

    I think the best approach is using #if-#endif preprocessor blocks to "comment" code. It transmits the idea that code was anulated on purppose:

    #if 0
      a = TEST;
      cout << a;
    #endif

    Even better, if you place a guard label instead the 0

    #define CODE_TO_TEST   0

    #if CODE_TO_TEST
    #pragma warning Code requires testing
      a = TEST;
      cout << a;
    #endif

    We can know exactly where and what is happening. I think this approach is much better and avoid some confusions, also enables the compiler to performs some checks, impossible to do with regular comments.

  • Samira Ferdi

    Hi Alex and nascardriver! I back to this lesson because I have issues about commenting and I don't know what should I gonna do with commenting if I try make a program.

    These are my issues:
    1. Should I give comment every line of my code?
    2. What's the difference 'bout "given/at" library, program, or function and "inside" library, program, or function? Could you give me examples?
    3. Why you explain WHAT at the function/library/program and HOW inside the function/library/program? What about if I explain both WHAT and HOW at the function/library/program or I explain both WHAT and HOW inside the function/library/program?
    4. What is the comments that put at the top - above any source code? I saw many source code that put comments at the top
    5. Library in C++ like file.cpp? What about if I have a libs folder that have many file.cpp, how can I give a comment to it?

    • nascardriver

      Hi Samira!

      1. No. See the "Proper use of comments" section.
      2. I don't understand.
      3.
      > Why you explain WHAT at the function/library/program and HOW inside the function/library/program?
      When you use a library you usually don't care how it's doing what it's doing, you care about how you use it and what the functions do. The 'what' comments are there for the user of the library, the 'how' comments are there for the developer of the library.
      > What about if I explain both WHAT and HOW at the function/library/program
      The user of your library doesn't care about how it's doing what it's doing, only tell them what they want to know.
      > I explain both WHAT and HOW inside the function/library/program
      'what' has to go in the header so you'd have duplicate comments.
      4.
      You either talk about file information (Created at date, Created by, Usage rights).
      You can ignore those, I assume they're used in development teams without version control.
      Or you're talking about documentation comments

      They are used to allow documentation generation so you have a nice overview of your code's functionality as a pdf or html.
      5. I don't understand.

      Alex is better at understanding questions than I am. If you give him a couple of days he might drop a comment. If he doesn't, you can try reformulating your questions and giving examples so I can understand them.

      • Samira Ferdi

        Thank you for replying, nascardriver! I really really appreciate that. This is my reformulated question for number 2 and 5.

        2. In the proper use of comments, Alex said that at library, program, and function describe 'what'. Inside the library, program or function describe 'how'. What is the difference betwen 'at' and 'inside'?

        5. The library is the collection of function, right? And the library usually a folder like libs folder. How can I comment 'what' at library (libs folder)?

        • nascardriver

          "At the library, program, or function"
          "At the library, program, or function level"
          The "level" makes a difference.

          "At the library, program, or function level"
          Means in the header file

          "Inside the library, program or function"
          Means in the source file

          > The library is the collection of function, right?
          A library can contain everything you can write in C++.

          > How can I comment 'what' at library (libs folder)?
          You'll usually have a main class (Not named "main", I mean the primary class) which you can use the describe the library as a whole. But you won't normally need to describe the library in your code, because if a user has your code he already knows what it's about, he wouldn't have downloaded it otherwise. The general library or program is described in a readme.md file. For example this one for Visual Studio Code
          https://github.com/Microsoft/vscode/blob/master/README.md

  • Alistair Ian McCall

    I am a 68-9 yrs. old absolute beginner, with no foreknowledge of the subject, but I am willing to learn.  I would be very happy for any pointers you may be able to offer.

    A. I. McCall

  • vinayak ruhela

    what is the work of comments?

  • Khaled Morgham

    Really, you have made me like programming in C++.  Thanx

  • anjali

    thanks for the lesson but i have a doubt, i didn't understand the purpose of multi line comment.please explain..

    • Alex

      Multiline comments are used when comments are lengthy. For example, if you're describing what a function does, that could take many lines. You could do that by using many single line comments in sequence, or one multi-line comment containing as many lines as you need.

      The following are really two ways of doing the same thing:

Leave a Comment

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