简体   繁体   中英

Can someone explain this Macro and function syntax in C?

I hate to ask this question, but I've never seen a macro quite like this following piece of code after 3 or 4 years of programming.

#define CREATE_FIXED_FIELD(Label, LabelFrame, ValueFrame, NextFrame, GetValue, SetValue, Digits, Fraction, Min, Max) \
{Label, LabelFrame, EditValue, ValueFrame, NextFrame, FixedDisplay, FixedBeginEdit, FixedFinishEdit, FixedKeyPressed, FixedHighlight, .fixed = {GetValue, SetValue, Digits, Fraction, Min, Max}}

Now I know you can use the define to create constants, but I never knew you could use them as a function. It's actually the second line with the curly braces that is throwing me off. What does it do exactly? Are the variables in the second line being set to the values in the first line? I would think it would be used as the function implementation, but that doesn't look to be the case. And lastly, what is the .fixed variable? I know it is a struct of some sort, but I have never seen a period used like that before in C . Is this define construct essentially a setter function?

It's a c99 designated initializer .

You can use it to initialize structure members (or array elements) in any order.

struct bla {
   int a;
   int b;
} x = { .a = 42, .b = 0};

You can specify only some members and any order. Omitted members are initialized as if they are static objects.

This macro is intended as a convenience when initializing a certain kind of structure. Assuming the structure definition is something like this:

typedef struct FixedField {
    char *label,
    Frame *labelFrame,
    // ...
    Fixed fixed,
    // ... Possibly more here ...
} FixedField;

Then you could use that macro to initialize a FixedField like this:

FixedField ff = CREATE_FIXED_FIELD(myLabel, myLabelFrame, /* ... */);

Whether it's better to use macros like this than proper functions depends on the details of the system. This way will consume more static program memory as it expands before compiling, but it will prevent pushing a new stack frame every time you initialize an object like this.

I find macros more difficult to debug than functions, but your mileage may vary.

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