Code Readability using Comments
Learn how to make the code understandable using comments.
Understanding code with comments
There’s another tool that we also can use to make things easier to understand for a person reading our code—comments.
Indentation and blank lines aren’t always enough to make the intent of the code clear. In these cases, we can use comments. A comment is a line of normal text inserted in the code, which is only for humans and is not compilable. We use them to explain lines of code that are not obviously understood at first glance.
The compiler or interpreter ignores comments, so we need a way to indicate that something is a comment. We have two variants of comments: one that runs to the end of the line, called a line comment, and one that spans multiple lines, often referred to as a block comment. Let’s learn about each of them in more detail.
Line comments
A line comment has some symbols indicating the beginning of the comment, and it continues for the rest of that line. These can be inserted on a separate line or at the end of a line of executable code. As a part of the language’s syntax, the symbol used to indicate the beginning of these comments is defined. Some are common, even if some languages will use more obscure variants.
The most common symbol used by many languages is a double slash, //
, which is two slashes without any space between them. Even if this symbol is made up of two characters, it’s treated as a single symbol. The languages that use this method for line comments include C, C++, C#, Go, Java, JavaScript, Kotlin,
and PHP.
Another common symbol used by a number of languages is the hash symbol, #
. Despite being a different symbol, it’s handled in the same way as the double slash. The hash symbol is used for line comments by languages such as Perl, Python, and Ruby.
Writing comments in some languages
Some languages have other ways to indicate a comment. In BASIC, the abbreviation REM (short for Remark) is used. Several BASIC versions have a variant as an option to ...