简体   繁体   English

C中的宏数组

[英]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位字段,其为零或垃圾。 (取决于编译器是否默认情况下初始化了一个字符)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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