Learn C++ with Qt, Part 009: Comments


Welcome back to my C++ with Qt tutorial! After having stressed the importance of proper initialization of variables in the previous part, I’d like to lose a few words about comments.  

A while ago I found a funny picture on programming.com with some pretty good advice on commenting and programming style. You can find the picture here - while it is funny, the advice makes a lot of sense, and should be kept in mind when you are working on your own programs.

Comments in programming

When you are writing a program in C++ or any other programming language, comments can be added to the source code of your program. The comment itself can contain any kind of text, you just have to mark the beginning and end of the comment so that the compiler knows how to distinguish between comment and usable source code.

Any properly defined comment is ignored by the compiler or interpreter when the program is compiled or executed. The comments are only visible for programmers who can access the source code of the program.

Why to use comments in source code

Just like in a human conversation, comments in the source code of a program are optional – the program works just as well without them.

But even with this in mind it makes a lot of sense to add comments to the source code of any program you are writing.

Comments make a source code more readable and easier to understand – at least if you add comments which make sense. This has some advantages:

  • you can easily understand your own code and change it even when you come back to it, which may be months or years later (when you may have forgotten a lot of the details)
  • other programmers can more easily understand how the program works and change it if they are tasked with maintenance of the program
  • with comments, the logical flow of the program can be more easily followed, which is useful for finding and fixing bugs
  • comments can contain headlines etc. which add more structure and overall readability to the code
  • when you comment your own program, it lets you think about your code more intensely - this often leads to code improvements

All in all, it’s good practice for any programmer to regularly add comments in the source code – not only when the code is part of a project that is created as a team effort by a larger group of programmers. 

Adding comments in C++

In the C++ programming language, there are (currently) two different ways how you can add comments in your source code. You can use both of them as long as you don’t mix them in the same comment block.

C-style comments

The first way to add comments is to use the classic C-style comments from the “C” programming language. In the C language, the start of a comment is marked by a slash followed by a star, like this: “/*”. After that, everything that follows is regarded as being part of the comment, up until the end marker. For the end marker, the two initial comment characters are written in reverse order, a star directly followed by a slash: “*/”. This is similar to comments in HTML.

Here is a short example for a C-style comment:

/* This is a comment. Don’t panic! */

C++ line comments

The second way for adding comments to the source code in C++ is the C++ line comment. Here you just need to add a double slash (“//”) in line of code. Everything that appears on the right side of the double slash is interpreted as a comment, up until the line break. The next line after this kind of comment is a normal line of code, and not regarded as being part of the previous comment.

A C++ line comment looks like this:

// This is a line comment. A=B+C is part of this comment.

Both comment types can be used within the same code file, depending on how and where you want to add comments. 

How to use comments in your source code

The C++ line comment is useful for documenting your source code. You can add a comment like a headline for a section of an article and tell any reader what the next block of code is about. 

You can also add comments right next to declarations or computations in order to explain in detail how your code and logic work. This can help to explain how certain variables, functions, object classes, methods etc. are used in the program, especially if their names are cryptic or too short to explain their purpose.

For larger comment blocks with more detailed comments or program documentation, the classic C-style comment is easier to use, unless you prefer to add a double slash to any line up to the end of the comment section. 

If you are debugging or changing a program, you can use both types of commenting to temporarily disable single lines or even a whole block of instructions in your code. For larger blocks of code, the C-style comment is especially useful. Code that is “commented out” (changed into comment text by adding comment markers) is not executed when the program is compiled and run again. This can be helpful in order to find the section where a logical error in your program is located (if it contains such an error).

Code commenting best practices

As programs can be very different from each other, and comments can contain any kind of text, including numbers, non-alphanumeric signs etc., there are usually no specific rules on where and how to add comments in your code (although some bigger software companies might have house rules for this).

Nevertheless, my experience with writing and maintaining different tools and applications on various computing platforms in the past has led me to develop some best practices that I try to use when I write new programs or change existing code written by other programmers. Here are my recommendations for commenting code:

  • Add a comment block at the start of a source code file that contains some basic information: the name of the file, the contents of the file, the author and date of creation. You can also add a change history or maintain this in a separate file for the whole project.
  • Add comment lines with basic headlines and minus or underline characters for optical separation between the main sections in your code, like type definitions, function definitions, class definitions, the main program etc. This added structure helps to navigate around the source code more easily.
  • Add comments to variable declarations that explain what kind of content the variables contain when the program is running.
  • Add comments at the beginning of procedures, functions and methods in order to describe what these parts of the program are intended to do.
  • Add comments to definitions of type, structure and class definitions describing what they contain and what they are used for in the program.
  • Add comments explaining the main parts of an algorithm that you use, so you and others can easily understand how this part of the program works. This also helps yourself to improve your code as you have to do more thinking about your code.
  • If you add some code to fix or avoid some kind of error condition (or check for it), add comments that explain the error and how you intend to avoid or handle it with this code.

You do not have to comment each line of code, just concentrate on the lines where someone other than you who reads the code later would likely not be able to directly understand what that part of the code does and how it fits in with the overall functionality of the program.

Beyond comments

What else can you do in order to make your source code more “readable”?

Naming conventions 

Naming conventions add more structure to your definitions of variables, types, object classes, functions etc. The idea here is to name all these different objects in a way that allows you to directly see what kind of object this is when you read the code again sometime in the future.

For example, you can add a prefix or a suffix to names of variables which directly show the data type of this variable, e.g. “i_count” or “intCount” for a counter variable that uses the integer type. 

The use of naming conventions for all commonly used objects in your code is definitely a good thing to do. If you work as part of a bigger team of programmers, there might already be several naming conventions in place that you can follow, otherwise you can create your own conventions. In the latter case, it’s a good idea to look at several different code examples on the web which are written in your programming language of choice, as this gives you a good idea about common conventions. 

Talking names

Together with naming conventions, the use of good, talking” names also adds more readability to your code.

A “talking” name is a name that instantly implies the content or functionality of a variable, structure, table, function etc. 

Let’s say you define two variables like this:

long a, b;

This allows you to use two variables called “a” and “b”, but it’s not clear what the variables are used for. They could be counters, some computed value, distances, measurements etc.

So instead of using rather abstract names you should use talking names:

long l_distance, l_velocity;

In this example, you can see that one variable here is used to store a distance value, while the other contains a velocity value, and both use the “long” data type. If you had several different distance and velocity values, you could use even more elaborate names like “l_distance_to_moon” or “l_velocityOfRocket”.

If you use more elaborate "talking" names for your variables, structure definitions, class or function names etc., make sure that each name is only composed of letters, numbers and only a few select symbols which are allowed for by the C++ programming language.

Specifically, you should not use things like the minus or plus signs as part of a name as these will not be considered to be part of the name, and will be interpreted as operators by the compiler. This only leads to errors in your program.

So make sure you use small and big alphanumerical characters and the underline character when you create a talking name for your objects etc.

Documentation

While more complex parts of your code can be documented and explained using whole blocks of comment lines, sometimes it makes sense to write an even more detailed documentation in the form of an external document that you create and maintain outside of the source code.

In some programming projects, such technical documents are a required part of the project. This is especially true if you are programming functions or services that are intended to be used by other programs and services. In this case, you have to create an application programming interface (API) for your own creation, and it has to be properly documented in order to be usable.

This kind of technical documentation can be written as a part of or completely independent of the user documentation for your application, depending on the kind of application and other specific details.

Final words

Even though it takes additional time to add comments to your code, you can save a lot of time with proper comments later on when you are debugging your program or trying to add new functionality to it, especially in combination with naming conventions, talking names etc.

So you should really try to make a habit out of regularly adding comments to your program during any kind of programming.

It takes time, and it does not add functionality to the program, but it is absolutely worth the additional effort.