简体   繁体   中英

static structure initialization with function pointers

I have initialized a structure of static with function name as shown below.

We have to initialize a static structure with constants. Is function names are constants in C?

struct fp {
        int (*fn)();
};
int f1()
{
        printf("f1 called \n");
        return 0;
}
static struct fp fps = {
        .fn = f1,
};
int main()
{
        fps.fn();
        return 0;
}

If is compiling without any issues when initialized the structure as shown below.

static struct fp fps = {
        .fn = &f1,
};

In C for a function name both f1 and &f1 are same?

f1 is the name of a function. In most contexts, when used as an expression, the function name decays automatically to a pointer to the function. One context where the decay doesn't happen is when the function name is the operand of the address-of operator ( & ). So as evaluated expressions, f1 and &f1 are usually the same.

In fact, in any function call expression f(args) , f is a pointer to a function. The reason that you can call functions simply by their name is because of the automatic decay from function name to function pointer.

You can turns this around and dereference function pointers, too. They'll decay back to a pointer right away:

int f(void);

f();         // "f" decays to &f
(&f)();      // normal call via function pointer, no implicit decay
(*f)();      // why not
(*****f)();  // ditto

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