Feature #1: Remove Comments
Explore how to implement a feature that removes inline and block comments from C++ source code before compilation. Learn to recognize comment patterns, manage nested comments, and discard empty lines after removal. This lesson teaches you to process code efficiently by traversing characters and maintaining state to output clean, comment-free code.
We'll cover the following...
Description
The first functionality we will be building will remove comments from a piece of code prior to its compilation. There are two types of comments in the C++ language, inline comments and block comments.
- Inline comment: The string
//is used for an inline comment, which means that the characters to the right of//in the same line should be ignored. - Block comment: The block comment is enclosed between the non-overlapping occurrence of
/*and*/. Everything inside these delimiters is ignored. Here, occurrences happen in reading order, meaning line by line from left to right. Note that the string/*/does not yet end the block comment because the ending would be overlapping the beginning.
Note: If two comments are nested, the first effective comment takes precedence over others. In other words, if the string
//occurs in a block comment, it is ignored. Similarly, if the string/*occurs in a line or block comment, it is also ignored. For example:
// this is an inline /* comment *//* this is a /* // block comment */
When implementing this feature, you have to detect the comments in the code first ...