简体   繁体   中英

Passing values to macros by for loop

I want to pass values to the macro through for loop,but when i try to pass values it gives error, please help m as fast as possible. When values of i are passed to macro as Valve(i) it gives error

my code given below:

#define Valve(x) stTest.bValve##x##_Cmd

typedef struct OperationFlags
{
   int bValve1_Cmd;
   int bValve2_Cmd;
}FLAGS_TypeDef;

void main(void)
{
  FLAGS_TypeDef stTest;
  int j,i;

  stTest.bValve1_Cmd = 4;
  stTest.bValve2_Cmd = 9;

  for(i=1;i<=2;i++)
  {
    j=Valve(1);
    printf("%d",j);
  } 

}

It is normal! The preprocessor (the "thing" that processes the macros) is run BEFORE the C compiler. So, it is only valid when it produces compilable code.

In your case, if you use the code you show

j=Valve(1)

it will work for that value, since it will produce:

j=stTest.bValve1_Cmd

but it will do the entire loop only with that value. When you change the parameter "1" with the "i" for actually doing the loop, then it will produce:

j=stTest.bValvei_Cmd

which is invalid.

To do what you want, just use a vector:

typedef struct OperationFlags
{
 int bValve_Cmd[2];
}FLAGS_TypeDef;
#define Valve(x) stTest.bValve_Cmd[x]
//....
for(i=1;i<=2;i++)
{
 j=Valve(1);
 printf("%d",j);
}

Macro replacement is done well before runtime, so you cannot use a variable X containing the value 2 to get stTest.bValve2_Cmd . Instead, you will get stTest.bValveX_Cmd , for which no symbol exists.

You will have to find another way of doing this, such as having an array of values for which you can use X to select:

#define Valve(x) stTest.bValveX_Cmd[x]

typedef struct OperationFlags {
   int bValveX_Cmd[2];
} FLAGS_TypeDef;

try this #define Valve(x) (x == 1 ? stTest.bValve1_Cmd : stTest.bValve2_Cmd)


#define Valve(x) (*(&stTest.bValve1_Cmd + (x-1)))

note : It may not work if the environment changes. Also it can not be used in the bit field.

add check

#define Valve(x) (*(&stTest.bValve1_Cmd + (x-1))); \
assert(offsetof(FLAGS_TypeDef, bValve2_Cmd) == sizeof(int))

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