This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Define act as function?

I've been using defines as fucntions like this:

sbit DRIVE_PIN05 = P1^3;

#define DRIVE_PIN05_HIGH (P1MDOUT |= 0x08);(DRIVE_PIN05 = 0)
#define DRIVE_PIN05_LOW (P1MDOUT |= 0x08);(DRIVE_PIN05 = 1)
#define DRIVE_PIN05_OFF (P1MDOUT &= 0xF7);(DRIVE_PIN05 = 1)

Is it there anything wrong with doing it like this?
It gives me problems when I include the above define into another define, why?

#define SUPPLY_ON (DRIVE_PIN05_HIGH);(DRIVE_PIN24_LOW)
#define SUPPLY_OFF (DRIVE_PIN05_OFF);(DRIVE_PIN24_OFF)

Maybe my syntax is incorrect or it can't be done?

Parents
  • "Maybe my syntax is incorrect or it can't be done?"

    For multi-statement macros, the convention is to wrap them with do/while(0). The parentheses are unnecessary.

    #define DRIVE_PIN05_HIGH do {P1MDOUT |= 0x08; DRIVE_PIN05 = 0;} while (0)
    #define DRIVE_PIN05_LOW  do {P1MDOUT |= 0x08; DRIVE_PIN05 = 1;} while (0)
    #define DRIVE_PIN05_OFF  do {P1MDOUT &= 0xF7; DRIVE_PIN05 = 1;} while (0)
    #define SUPPLY_ON        do {DRIVE_PIN05_HIGH;DRIVE_PIN24_LOW;} while (0)
    #define SUPPLY_OFF       do {DRIVE_PIN05_OFF; DRIVE_PIN24_OFF;} while (0)
    

Reply
  • "Maybe my syntax is incorrect or it can't be done?"

    For multi-statement macros, the convention is to wrap them with do/while(0). The parentheses are unnecessary.

    #define DRIVE_PIN05_HIGH do {P1MDOUT |= 0x08; DRIVE_PIN05 = 0;} while (0)
    #define DRIVE_PIN05_LOW  do {P1MDOUT |= 0x08; DRIVE_PIN05 = 1;} while (0)
    #define DRIVE_PIN05_OFF  do {P1MDOUT &= 0xF7; DRIVE_PIN05 = 1;} while (0)
    #define SUPPLY_ON        do {DRIVE_PIN05_HIGH;DRIVE_PIN24_LOW;} while (0)
    #define SUPPLY_OFF       do {DRIVE_PIN05_OFF; DRIVE_PIN24_OFF;} while (0)
    

Children
  • I forgot to mention that the style convention for function-like macros is to have them look like function invocation where they are used; that is, with a parameter list that is optionally empty.

    #define SUPPLY_ON()      do {DRIVE_PIN05_HIGH;DRIVE_PIN24_LOW;} while (0)
    #define SUPPLY_OFF()     do {DRIVE_PIN05_OFF; DRIVE_PIN24_OFF;} while (0)
    
    void supply(unsigned char on) {
        if (on)
            SUPPLY_ON();
        else
            SUPPLY_OFF();
    }