1. 程式人生 > >C語言中反斜槓的作用

C語言中反斜槓的作用

反斜槓起到換行作用,用於巨集定義和字串換行。其中巨集定義中使用居多。

如果一行程式碼有很多元素,導致太長影響閱讀,可以通過在結尾加\的方式,實現換行,編譯時會忽略\及其後的換行符,當做一行處理。

1、在巨集定義中,要換行必須使用 \ 結尾。

#define CHECK_ACTION_RETURN(expr) \
    if (!expr) { \
        printf(":failed(%d)\n", ret); \
        return ret; \
                } else { \
        printf(":ok\n"); \
                }

2、在字串常量中,可以使用 \ 結尾。

"this \
is \
for \
testing"

和”this is for testing”是相同的,但是對於字串寫成

"this "
"is "
"for "
"testing"

效果是相同的,而且更美觀。

3、另外,在普通的語句中,也可以通過 \ 實現換行,不過這時沒有 \ 也是一樣的效果
比如

printf("this is for test %d %d %d\n",\
test_output_a,\
test_output_b,\
test_output_c);

printf("this is for test %d
%d %d\n"
, test_output_a, test_output_b, test_output_c);

是沒有區別的,所以這時一般不會使用\。