简体   繁体   中英

Array of macros in C

Can I do array of macros

I am trying to define array of macros, Please check the below code and let me know can I do it like this:

#include <stdio.h> 

struct da
{
    unsigned char d1:1;
    unsigned char d2:1;
};

struct da stDataVar;

#define DATA_1 stDataVar.d1
#define DATA_2 stDataVar.d2 = 1

unisgned char arrChar[2] = {DATA_1, DATA_2};

main()
{
 
printf("data = %d\n",arrChar[0]);

}

It doesn't make any sense to have "an array of macros". In your case, the macros probably just obfuscate the code. In particular, you shouldn't hide side effects inside macros that you are using for initialization.

Is there any reason why you can't do like this?

// elsewhere in the code:
stDataVar.d2 = 1;

...

unsigned char arrChar[2] = 
{ 
  stDataVar.d1,
  stDataVar.d2
};

arrChar [0]是arrChar [2]的第一个元素,即DATA_1,这是一个宏,该宏在文本上被预处理器替换为stDataVar.d1,这是结构stDataVar(类型struct da)的d1位字段,其为零或垃圾。 (取决于编译器是否默认情况下初始化了一个字符)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM