c 反斜杠在注释中被忽略

c backslash ignored in comment

我对 C 语言中注释末尾的反斜杠被忽略的行为感到困惑,如下所示。正如您在评论后看到的那样, "comment 2: Dummy" 末尾有一个反斜杠。我期待的是一个编译错误,但没有得到任何。我正在使用 Greenhills 编译器。但此行为仅适用于“\”字符。如果我使用其他东西,编译器会生成错误。

#include <stdio.h>

int x =0;
int y =2;


#define MACRO(x) (x+y)\
/*comment 1: Do addition of two operations*/ \
               +\
            (x*y)

/*comment 2: Dummy */\  <=============== Backslash at the end 

#define MACRO1(y) (x+y)\
/*comment 3: Do Sub of two operations*/ \
            -\
            (x*y)

int main()
{
    x = MACRO(x);
    printf("value is : %d",x);
    y = MACRO1(y);
    printf("value is : %d",y);
    return (0);
}

backslash ignored in comment

两件事:

  • 不在评论
  • 应该被忽略,难怪。

详细说明,引用 C11,章节 §6.4.9

Except within a character constant, a string literal, or a comment, the characters /* introduce a comment. The contents of such a comment are examined only to identify multibyte characters and to find the characters */ that terminate it.

因此,在您的情况下,\ 在注释之外,被视为源代码的一部分。

现在,考虑到 stray 反斜杠,如翻译阶段所述,章节 §5.1.1.2/p2

Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. [....]

因此,在您的情况下,在到达 actual 编译阶段时 有效地 删除了杂散的反斜杠和随后的换行符,因此有那里没有错误。

You can read more about the compilation phases here.

中,写多行宏,每条语句以\结束。在您的第二行中,注释在 /* COMMENT */ 内定义。因此,除此之外的任何内容都是语法,\ 是有效语法。

这就是为什么您的编译器可以使用 \

额外的 \ 是无关紧要的,编译器会忽略,因为没有语句进入。

您可以添加任意多的 \,您的编译器生成的代码将是相同的。

#include <stdio.h>

int x =0;
int y =2;


#define MACRO(x) (x+y)\
/*comment 1: Do addition of two operations*/ \
               +\
            (x*y)
 \
\
\
\

int main()
{
    x = MACRO(x);
    printf("value is : %d",x);
    return (0);
}

以及生成的代码:

    .file   "Untitled1.c"
    .globl  _x
    .bss
    .align 4
_x:
    .space 4
    .globl  _y
    .data
    .align 4
_y:
    .long   2
    .def    ___main;    .scl    2;  .type   32; .endef
    .section .rdata,"dr"
LC0:
    .ascii "value is : %d[=11=]"
    .text
    .globl  _main
    .def    _main;  .scl    2;  .type   32; .endef
_main:
LFB10:
    .cfi_startproc
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    andl    $-16, %esp
    subl    , %esp
    call    ___main
    movl    _x, %edx
    movl    _y, %eax
    leal    (%edx,%eax), %ecx
    movl    _x, %edx
    movl    _y, %eax
    imull   %edx, %eax
    addl    %ecx, %eax
    movl    %eax, _x
    movl    _x, %eax
    movl    %eax, 4(%esp)
    movl    $LC0, (%esp)
    call    _printf
    movl    [=11=], %eax
    leave
    .cfi_restore 5
    .cfi_def_cfa 4, 4
    ret
    .cfi_endproc
LFE10:
    .ident  "GCC: (GNU) 5.3.0"
    .def    _printf;    .scl    2;  .type   32; .endef