Can you give me examples of odd single line comments in C++?

无人久伴 提交于 2019-12-12 01:33:30

问题


I wrote a method to remove single line comments from a C++ source file:


def stripRegularComments(text) {
  def builder = new StringBuilder()
  text.eachLine {
   def singleCommentPos = it.indexOf("//")
   def process = true
   if(singleCommentPos > -1)
   {
    def counter = 0
    it.eachWithIndex 
    { obj,i ->
     if((obj == '\'') || (obj == '"'))
      counter++
     if(i == singleCommentPos)
     {
      process = ((counter % 2) == 1)
      if(!process)
       return
     } 
    }

if(!process)
{
 def line = it.substring(0,singleCommentPos)
 builder << line << "\n"
}
else
{
 builder << it << "\n" 
}

} else { builder << it << "\n" } } return builder.toString() }

And I tested it with:

println a.stripRegularComments("""
this is a test inside double quotes "//inside double quotes"
this is a test inside single quotes '//inside single quotes'
two// a comment?//other
single //comment
""")

It produces this output:

this is a test inside double quotes "//inside double quotes"
this is a test inside single quotes '//inside single quotes'
two
single

Are there some cases I'm missing?


回答1:


The fun ones are formed by trigraphs and line continuations. My personal favorite is:

/??/
* this is a comment *??/
/



回答2:


// Single line comments can\
actually be multi line.



回答3:


I think you can't handle

  puts("Test \
    // not a comment");

and this is also likely to make problems:

  puts("'"); // this is a comment



回答4:


You don't seem to handle escaped quotes, like:

"Comment\"//also inside string"

versus

"Comment"//not inside string"



回答5:


I think you are missing the /* comment */ case.




回答6:


The handling of \ character at the end of the line is performed at the earlier translation phase (phase 2) than replacement of comments (phase 3). For this reason, a // comment can actually occupy more than one line in the original source file

// This \
whole thing \
is actually \
a single comment

P.S. Oh... I see this is already posted. OK, I'll keep it alive just for mentioning phases of translation :)




回答7:


This is always a favourite:

// Why doesn't this run?????????????????????/
foo(bar);


来源:https://stackoverflow.com/questions/1618419/can-you-give-me-examples-of-odd-single-line-comments-in-c

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