我对C语言中的一种行为感到困惑,在这种行为中,注释末尾的反斜杠被忽略,如下所示。正如你在评论后看到的,“注释2:哑”后面有一个反斜杠。我所期待的是一个编译错误,但没有得到任何。我正在使用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);
}发布于 2017-03-13 07:02:09
注释中忽略的反斜杠
有两件事:
详细阐述,引用C11,第6.4.9节
除了在字符常量、字符串文本或注释中,字符
/*引入注释。这样的注释的内容只用于识别多字节字符和找到终止它的字符*/。
因此,在您的示例中,\位于注释之外,并被视为源代码的一部分。
现在,考虑到在翻译阶段所提到的不稳定反斜杠,第5.1.1.2/p2章
每一个反斜杠字符(
\)的实例后面紧跟一个新行字符,将物理源行拼接成逻辑源行。只有任何物理源线上的最后一个反斜线才有资格成为这种拼接的一部分。……
因此,在您的示例中,在达到实际编译阶段时,会有效地删除偏离反斜杠和后面的换行符,因此不会出现错误。
发布于 2017-03-13 07:02:35
在C中,要编写多行宏,每个语句都以\结尾.在第二行中,注释是在/* 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\0"
.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 $16, %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 $0, %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; .endefhttps://stackoverflow.com/questions/42757976
复制相似问题