C/C++ comments (annotated)

參考 https://en.cppreference.com/w/c/comment整理一些注意的重點

All comments are removed from the program at translation phase 3 by replacing each comment with a single whitespace character.

這裡描述在translation phase3對於comment做的事,用一個space character取代

translation phase 3可參考C99 § (p.10)

3. The source file is decomposed into preprocessing tokens6) and sequences of white-space characters (including comments). A source file shall not end in a partial preprocessing token or in a partial comment. Each comment is replaced by one space character. New-line characters are retained. Whether each nonempty sequence of white-space characters other than new-line is retained or replaced by one space character is implementation-defined

Except within a character constant, a string literal, or a comment, the characters /* introduce a comment.
這邊解釋為什麼 嵌套 /* /* */ */ 會不對稱的原因,因為第二個 /* 已經在 comment內,所以第一個/* 會 match 倒數第二個*/,而留下最後一個不對稱的 */

關於為什麼語言設計時不設計成支援嵌套的原因可參考,http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf 6.4.9

主要的原因是C89的committee認為有其他方式可以處理nested comment,也可參考 comment tips這邊的說明

像上面這種註釋法採用conditional directive有時也被稱為conditioned out,要注意的是 c comment /* */ 的取代還有preprocessing token解析等是在執行preprocessor前進行,所以這邊的#if 0, #endif 的內容一開始也會被處理。

winged comments: 單行 /* */ 註解,相對於boxed comments

 * This is a boxed comment in C style
This entry was posted in C Language. Bookmark the permalink.

Leave a Reply