C – Comments

Course Outline  | Previous LessonNext Lesson

Introduction – Purpose of C Comments

C comments are mainly used for describing the semantics of each parts of your code. They can help organize your code, and they will help make your code readable to other programmers. You will most likely work with teams while creating software so it is crucial that your code has comments.

Three Types of Comment

We will reuse the code from the previous lecture and add three types of comment. Please refer to the code below.

/**
 * This comment can be used for documentation of the C file. This type 
 * of comment can be used to describe features of this particular C file. 
 * In addition, this comment can be used for stating who wrote this code
 * and who owns the file. This type of comment is usually placed at the very 
 * top of the C file.
 */
#include <stdio.h>

/* This comment can describe the semantics of your code. This comment can 
extend to multiple lines like the previous comment above */
int main(void)
{
     printf("Hello World!");   // Use this type of comment if comment is short.
     return 0;
}

Note that the first two comments from the program above need to be closed off with the closing sequence of characters (*/). If you forget to close those kinds of comment off, the compiler would think your code is a comment too. Be sure to always close them off.

The third comment (inline comment) from the program above does not require you to close it off directly because the comment only last one line. That is why the the inline comment is best if the comment itself is short.

How Computers Treat Comments

Computers ignore comments while executing the file above. Whenever the computer encounters the sequence of characters that starts the comments, the computer does not execute anything until after it reaches the sequence of character (for the first two comments in the program above) or a newline character (inline comments) that ends the comment. As a result, it is like the comments do not exist to the computers.

Conclusion

Comments are imperative in programming since it helps to make code readable. They can also help organizing the code. There are three types of comment. The first one is for documenting the file, which it would describe the general functionality of the C file. The first one can also be used for stating who wrote the code, who owns it, and more. The second one is used to describe the semantics of code, and this type of comment would be a better choice if the comment itself extends more than one line. The third one is the inline comment. Using an inline comment would be a better choice if the comment itself is short. Always include comments while programming even when practicing.

Course Outline  | Previous LessonNext Lesson

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz