函数作为结构体成员变量

#include<stdio.h>

typedef struct A
{
int a;
char b;
} foo;
int f2()
{
printf("this is f2 ");
return 2;
}

void f3(int x,char y)
{
printf("this is f3 + %d +%c ",x,y);
}

int main(int argc, char *arg[])
{
foo f1[]=
{
{f2(),'A'},
{f2(),'B'},
{f2(),'C'}
};

f3(f1[1].a,f1[1].b);

}

其中f2()这个函数作为f1()这个结构体的成员变量,打印结果如下:

-bash-3.2$ ./a.out
this is f2
this is f2
this is f2
this is f3 + 2 +B

可以看到,当定义f1这个数组的时候,f2()这个函数被执行了3次。

原文地址:https://www.cnblogs.com/miry/p/5583003.html