0

I'm fairly new to C and only just stumbled onto Compound Literals so please correct me if my question is inaccurate.

I have a struct;

typedef struct
{
  int someVal;
} foo;

Now I understand this could be initialized with the following.

int main()
{
  foo thisFoo = (foo) { .someVal = 2 };
}

My question is, could I initialize someVal with a void function?

void init(int *f);

int main()
{
  foo thisFoo = (foo) { init(.someVal) }; // error: expected expression before '.' token
}

void init(int *f)
{
  *f = 2;
}

I've managed to initialize the struct itself and its respective members in a function without any problems but was curious if this is an alternative (or even reasonable) choice?

1 Answers1

0

No, you can't initialize like that. You could create the structure without initialization, and then call the function with the address of the member.

foo thisFoo;
init(&thisFoo.someVal);
Barmar
  • 741,623
  • 53
  • 500
  • 612