Array of macros in c — is it possible

前端 未结 2 866
一向
一向 2021-01-22 02:38

I was wondering if it is possible to create something like an array of macros. I\'ve implemented the following code which works:

struct led_cmds_
{ 
    ioport_pi         


        
相关标签:
2条回答
  • 2021-01-22 03:16

    You need to work on your terminology. An array of macros is not possible. Macros are no data type, but rather pure text replacement before your program is actually compiled.

    I guess " populate an array using macros " is what you want to do. But it is not possible to do that in a compile-time loop - What you seem to want to achieve with your ioport_pin_t macro attempt. Macros do not have the capability to expand to more instances of text elements than you have initially given. There is no such feature as looping at compile time through macro expansions and do repetitive expansion of macros.

    Your for loop loops at run-time, while the macro is being expanded at compile-time. Once you have made yourself aware what is done by the preprocessor what is done by the compiler, and what is done at run-time by the finished program, you will see that will not work.

    Something like

    #define P(X) {(LED##X##_PIN)}
    
    ioport_pin_t *commands[LED_COUNT] = {
      P(0), P(1), P(2),......}
    
    #undefine P
    

    Would be the closest thing possible to what you seem to want. Note the main use of the pre-processor is not to save you typing effort - You would be better off using copy & paste in your editor, achieve the same thing and have clearer code.

    0 讨论(0)
  • 2021-01-22 03:25

    An array as tofro's answer is the way to go. However in cases that couldn't be solved simply with an array then there's another way with switch

    #define SPECIFICPIN(X) (LED##X##_PIN)
    
    void setpin(int pin, int value)
    {
        switch (pin)
        {
        case 1:
            SPECIFICPIN(1) = value;
            doSomething(); // if needed
            break;
        case x: ...
        default: ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题