c語言多行巨集定義及其注釋

2021-06-21 01:30:05 字數 1965 閱讀 6530

早上在寫**時遇到這樣乙個問題:即如何在乙個擁有多行的巨集定義中做注釋?,這裡把方法演化的過程貼出來,可能對某些朋友有些借鑑意義。

巨集定義高深莫測,而且是比較細節的東西,詳細說明請參見"c參考手冊"之類的書籍。

在我的**中,我大致要做這樣乙個簡單的事情:printf("%s%s%s\n", "hello", "macro", "yeah!"); "%s%s%s\n"這個字串中每一項輸出都有一定的含義,而且在真實**裡,這個串中的輸出項可不止3個,所以乙個直接的想法就是將其定義為乙個巨集。

#define str_output_format_v0  "%s%s%s\n"

printf(str_output_format_v0, "hello ", "macro, ", "yeah!");

程式輸出:hello macro, yeah!

由於真實**中這個串很長,所以打算美化一下格式,定義成下面的樣子:

#define str_output_format_v1  "%s\

%s\%s\n"

printf(str_output_format_v1, "hello ", "macro, ", "yeah!");

程式輸出:hello                                macro,                                yeah!

這樣的定義顯然不對,也在我意料之中,續行符將空格也續到格式串中了,導致輸出的結果中帶有大量空格。

改進一下,利用c語言的字串自動連線語法。

#define str_output_format_v2  "%s"\

"%s"\

"%s\n"

printf(str_output_format_v2, "hello ", "macro, ", "yeah!");

程式輸出:hello macro, yeah!

#define str_output_format_e1  "%s"\   /* comment1 */

"%s"\   /* comment2 */

"%s\n"  /* comment3 */

printf(str_output_format_e1, "hello ", "macro, ", "yeah!");

我們得到的結果:編譯錯誤。

通過gcc -e 選項我們看到,巨集替換後的**:

"%s"\

"%s\n"

int main()

由於沒有續行符在注釋前面,所以巨集定義的後兩行實際上並沒有被包含在巨集定義中,就像沒有暫住證的人一樣,被gcc這個"警察"逮個正著。

繼續改進:

#define str_output_format_v3  "%s"   /* comment1 */ \

"%s"   /* comment2 */ \

"%s\n"  /* comment3 */

printf(str_output_format_v3, "hello ", "macro, ", "yeah!");

程式輸出:hello macro, yeah!

顯然預編譯器忽略巨集定義中的注釋以及空格,str_output_format_v3就完全符合我的要求了。

當然,很多人不建議使用巨集,特別是c++的fans,巨集也的確有很多弊端,這裡也有替代方法:

const char *str_output_format = "%s"    /* comment1 */

"%s"    /* comment2 */

"%s\n"; /* comment3 */

printf(str_output_format, "hello ", "macro, ", "yeah!");

程式輸出:hello macro, yeah!

用乙個字串變數代替格式巨集,還可以避免上述由於在巨集中做注釋帶來的一系列問題

jsp 單行注釋多行注釋 C語言的注釋

c語言中,注釋有兩種型別 單行注釋 單行注釋通常用於對程式中的某一行 進行解釋,用 符號表示,後面為注釋的內容 示例 printf hello,worldn 輸出hello,world 多行注釋 多行注釋就是注釋中的 可以為多行,以符號 開頭,以符號 結尾 示例 printf hello,world...

source insight 巨集注釋巨集定義

source insight si 中有乙個base工程,是安裝完si後自動生成的乙個工程,該工程裡只有乙個utils.em檔案,該檔案是常用編輯巨集的乙個集合。通過修改或新增巨集就可以讓巨集實現我們想要在編輯文字時新增的內容。檔案注釋 macro insertfileheader 函式注釋 mac...

C語言巨集定義函式的使用 定義單行和多行)

要寫好c語言,漂亮的巨集定義是非常重要的。巨集定義可以幫助我們防止出錯,提高 的可移植性和可讀性等。在軟體開發過程中,經常有一些常用或者通用的功能或者 段,這些功能既可以寫成函式,也可以封裝成為巨集定義。那麼究竟是用函式好,還是巨集定義好?這就要求我們對二者進行合理的取捨。巨集定義中允許包含兩行以上...