Can't pass a `#define` as function argumant but can pass array[n] of `#define`

Viewed 88

I have a structure which is:

typedef struct {
    GPIO_TypeDef* port;
    uint16_t pin;
} btn;

Some definitions:

#define BTN0    {App_BTN_GPIO_Port, App_BTN_Pin}
#define BTN1    {Calibration_BTN_GPIO_Port, Calibration_BTN_Pin}
//...

An array of buttons:

btn btns[] = {BTN0, BTN1, ...}

Also a function:

bool checkPressAndReleaseWithMask(btn button){
    if (HAL_GPIO_ReadPin(button.port, button.pin) == GPIO_PIN_RESET) {
        //bla bla bla
    }
}

I have the below problem. When I want to call this function, I can't pass my definitions:

btn find1BTN()
{
    btn test = {App_BTN_GPIO_Port, App_BTN_Pin};
    
    if(checkPressAndReleaseWithMask(btns[0])){ //allright

    } else if (checkPressAndReleaseWithMask(test)){ //allright
        
    } else if (checkPressAndReleaseWithMask(BTN0)){ //PROBLEM
        
    }
    
    return test;
}

btn[0] and test work fine, but the BTN0 does not. I've also tried:

    if (checkPressAndReleaseWithMask({.port = App_BTN_GPIO_Port, .pin = App_BTN_Pin})){ //PROBLEM
            
    }

The same compile-time problem:

error: expected expression

Why does this happen? What's the difference between BTN0 and btn[0]? They seem to be the same!

How about the {.port = App_BTN_GPIO_Port, .pin = App_BTN_Pin}? As I remember, we could pass structs this way, couldn't we?

I also checked this. It was not my problem.

NOTE: Feel free to change the topic. I couldn't find any better one.

1 Answers

The correct syntax for a compound literal is:

( type ) { initializer-list }

So the code needs to be:

checkPressAndReleaseWithMask((btn)BTN0);

Or

#define BTN0 ((btn){App_BTN_GPIO_Port, App_BTN_Pin})
checkPressAndReleaseWithMask(BTN0);
Related