How compiler recognise the single line comments? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

How compiler recognise the single line comments?

As the compliers ignores blank space & new lines (unless it is \n, endl or semicolon ( ; ). I am confused how does the compiler recognise the single line comment. for ex. in the below code - { // cout<<"Hello" cout<<"World"; } above program will only print "world". but how does the compiler know where the first line ends, because it is said that compiler ignores blank spaces & new line unless it is semicolon (;)

15th Aug 2017, 5:08 AM
Suyog Naikwade
Suyog Naikwade - avatar
5 Answers
+ 4
For a standard c or c++ compiler the process of converting the source code into an executable file, is done in multiple steps by multiple components. In order: preprocessor, compiler, assembler, then linker. The preprocessor replaces all the #include and #define statements with the correct code. The compiler uses this adjusted code as it's source. Note the preprocessor statements are line operated. Normally the preprocessor will replace the comments with a space. So the compiler never sees the comments at all.
15th Aug 2017, 8:41 AM
Jared Bird
Jared Bird - avatar
+ 10
The job of the compiler is to take that source file (cpp file), check it line by line for possible syntax errors, and transform it into a corresponding sequence of machine-level instructions. This is why the compiler is able to identify error on specific line. In this process, single-line/multi-line comments are also identified.
15th Aug 2017, 5:24 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Yeah. Compiler have something called parser which is a routine that analyse your code and based on pre-defined grammar (written by compiler designer) identify different elements of language such as evaluating the variable name to see it begins with a letter or underscore and not a number.
15th Aug 2017, 5:33 AM
Babak
Babak - avatar
+ 4
I built a compiler for one of my classes at University. The way compilers work is in three stages. 1) A lexical analyzer determines what components are in the code 2) A syntax tree is created 3) Machine code is generated from this tree A single line comment will be caught as "\\" and the section between this and the "\n" newline escape is determined to be a comment by the Lexical Analyzer. Here it will be filtered out before it reaches the second stage.
15th Aug 2017, 6:39 AM
S C
+ 3
I think we can rephrase it as *no effect* instead of *ignore* as the compiler still read the code line-by-line. (that's why we have both single & multi-line comments) So essentially if you're going to compress the entire program into a one-liner, the single line comment wouldn't work in this case. 😉
15th Aug 2017, 6:38 AM
Zephyr Koo
Zephyr Koo - avatar