如何定义跨行的宏

宏定义只能在一行

  • 如果宏定义有多行的话,编译器会报错。如下:
// 宏定义,定义了多行
#define insert_item(item,ps) do{
	item->prev = NULL;
	item->next = ps;
	if(ps != NULL) ps->prev = item;
	ps = item;
} while(0)
// 会报如下错 
content.c:17:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
  item->prev = NULL;
      ^~
content.c:18:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
  item->next = ps;
      ^~
content.c:19:2: error: expected identifier or ‘(’ before ‘if’
  if(ps != NULL) ps->prev = item;
  ^~
content.c:20:2: warning: data definition has no type or storage class
  ps = item;
  ^~
content.c:20:2: warning: type defaults to ‘int’ in declaration of ‘ps’ [-Wimplicit-int]
content.c:20:7: error: ‘item’ undeclared here (not in a function); did you mean ‘system’?
  ps = item;
       ^~~~
       system
content.c:21:1: error: expected identifier or ‘(’ before ‘}’ token
 } while(0)
 ^
content.c:21:3: error: expected identifier or ‘(’ before ‘while’
 } while(0)
   ^~~~~

如何解决

  • 加个反斜杠就好了。因为加了反斜杠后,编译器会自动忽略行尾的换行符。编译器会认为这几行的代码都是在一行里。
// 加上反斜杠
#define insert_item(item,ps) do{\
	item->prev = NULL;\
	item->next = ps;\
	if(ps != NULL) ps->prev = item;\
	ps = item;\
} while(0)

你可能感兴趣的:(c语言,c++)