-1

I have code like this:

typedef enum {
    API_SIG_SERVER_CONNECTED = 1,
    API_SIG_DATA_RECEIVED,
} api_signals_t;

typedef struct {
    api_signals_t signal;
    void * params;
} api_msg_t;

static void send_msg_to_api(api_msg_t * p_msg){
    // do something
}

void main(){
    api_msg_t msg = {API_SIG_SERVER_CONNECTED, 0};
    send_msg_to_api(&msg);
}

Can I make this part shorter without macro?

api_msg_t msg = {API_SIG_SERVER_CONNECTED, 0};
send_msg_to_api(&msg);

This is not possible:

send_msg_to_api({API_SIG_SERVER_CONNECTED, 0});

This is possible but ugly:

send_msg_to_api(&((api_msg_t){API_SIG_SERVER_CONNECTED, 0}));

Is there other way to do structure initialization and function call in single line?

I could wrap this in a macro to make it pretty, or rewrite send_msg_to_api function to take 2 parameters and initialize struct inside, but this is not my point. I'm learning C and I would like to know if there is some "pretty" way of doing this.

Kamil
  • 13,363
  • 24
  • 88
  • 183

1 Answers1

2

What you've tried are pretty much your only options. The only thing I see is that you have one extra set of parenthesis in the compound literal example you can get rid of:

send_msg_to_api(&(api_msg_t){API_SIG_SERVER_CONNECTED, NULL});

Also, you should generally use NULL for a null pointer instead of the constant 0, as it makes it more clear what your intent is.

dbush
  • 205,898
  • 23
  • 218
  • 273