在定義結構體時進行宏定義,其作用域從定義處開始直至文件結束
與結構體外的同名宏定義會有redefine的warning,新的定義會覆蓋之前的定義
其作用是告知源代碼閱讀者,該宏定義是爲了該結構體中變量而定定義,如下代碼中,MAY和JUNE宏定義是用於變量month使用。
#include<stdio.h>
#define MAY 0
typedef struct test
{
int month;
#define MAY 5
#define JUNE 6
int day;
}TEST;
#define JUNE 0
int main()
{
TEST a;
printf("&month = %x\n&day = %x\nMAY = %d\nJUNE = %d\n", &a.month, &a.day, MAY, JUNE);
return 0;
}
關於宏定義,如下告警
testmacro.c:7:0: warning: "MAY" redefined [enabled by default]
#define MAY 5
^
testmacro.c:3:0: note: this is the location of the previous definition
#define MAY 0
^
testmacro.c:12:0: warning: "JUNE" redefined [enabled by default]
#define JUNE 0
^
testmacro.c:8:0: note: this is the location of the previous definition
#define JUNE 6
^
程序運行結果如下
&month = 99f791e0
&day = 99f791e4
MAY = 5
JUNE = 0