微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何定义跨行的宏

宏定义只能在一行

  • 如果宏定义有多行的话,编译器会报错。如下:
// 宏定义,定义了多行
#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)

原文地址:https://www.jb51.cc/wenti/3284474.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐