C语言高级编程:接续符'\'的用法

接续符(\)表示断行。

1)编译器将反斜杠剔除,跟在反斜杠后面的字符自动接续到前一行

2)接续单词(函数名、关键字、变量等)时,反斜杠之后不能有空格,反斜杠下一行之前也不能有空格。如果不是接续单词,如定义函数宏,反斜杠下一行之前可以有空格,但反斜杠之后最好也没有空格,否则编译会产生警告。

3)接续符适合在宏定义代码块时使用(不可以不使用,否则编译会报错)

测试平台:64位 X86 Ubuntu

1. 如下编译通过:

#include<stdio.h>
void main()
{
    pri\
ntf("hello world\n");
}

2. "ntf"前有空格,编译会提示错误:

#include<stdio.h>
void main()
{
    pri\
    ntf("hello world\n");
}
baoli@ubuntu:~/c$ gcc test.c
test.c: In function ‘main’:
test.c:6:5: error: unknown type name ‘pri’
     pri\
     ^
test.c:7:9: error: expected declaration specifiers or ‘...’ before string constant
     ntf("hello world\n");
         ^

3. 定义函数宏:

#include <stdio.h>


#define SWAP(a,b)  \
{                  \
    int temp = a;  \
    a = b;         \
    b = temp;      \
}

int main()
{
    int a = 1;
    int b = 2;
    int c = 3;

    SWAP(a,b);
    printf("a = %d, b = %d\n", a, b);
    SWAP(b,c);
    printf("b = %d, c = %d\n", b, c);

    return 0;
}
  • 定义函数宏时必须加上花括号{},或者采用do-while(0)结构,参考 do{...}while(0)的妙用,推荐采用do-while(0)结构

  • #define 指令只能写在一行,不管用不用花括号都是这样,要写到多行必须要用续行符 \,将所有行内容拼接待一行中

  • 也可以不用接续符,把他们写到一行,但是代码可读性会非常差!

注意,不能去掉花括号,采用如下的写法

#define SWAP(a,b)  \
    int temp = a;  \
    a = b;         \
    b = temp;  

否则编译会产生错误:重复定义temp变量

发布了170 篇原创文章 · 获赞 116 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/u012247418/article/details/102371819
今日推荐