Do comments get translated to machine code? C++

▼魔方 西西 提交于 2019-12-10 10:59:13

问题


When a program written in C++ has comments, are those comments translated into machine language or do they never get that far? If I write a C++ program with an entire book amount of comments between two commands, will my program take longer to compile or run any slower?


回答1:


Comments are normally stripped out during preprocessing, so the compiler itself never sees them at all.

They can (and normally do) slow compilation a little though--the preprocessor has to read through the entire comment to find its end (so subsequent code will be passed through to the compiler. Unless you include truly gargantuan comments (e.g., megabytes) the difference probably won't be very noticeable though.

Although I've never seen (or heard of) a C or C++ compiler that did it, there have been compilers (e.g., for Pascal) that used specially formatted comments to pass directives to the compiler. For example, Turbo Pascal allowed (and its successor probably still allows) the user to turn range checking on and off using a compiler directive in a comment. In this case, the comment didn't (at least in the cases of which I'm aware) generate any machine code itself, but it could and did affect the machine code that was generated for the code outside the comment.




回答2:


No, they are simply ignored by the compiler. Comments' sole purpose is for human reading, not machine.




回答3:


The preprocessor eliminates comments.. Why should the compiler read them anyway? They are there to make it easier for people to understand the code.. Haven't you heard the joke "It's hard to be a comment, you always get ignored" :p




回答4:


In the 3rd translation phase

  • The source file is decomposed into comments, sequences of whitespace characters (space, horizontal tab, new-line, vertical tab, and form-feed), and preprocessing tokens.

  • Each comment is replaced by one space character.

See this cpprefference article for more information about the phases of translation




回答5:


No , they are removed by the preprocessor .You can check this by using cpp: The C Preprocessor . Just write a simple C-program with comment and then use cpp comment.c | grep "your comment" .



来源:https://stackoverflow.com/questions/28950718/do-comments-get-translated-to-machine-code-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!