2

I should first say I don't think what I want to do is possible (having read what I think are the relevant parts of the ISO C99) but here is rough idea of what I have now:

struct foo {
    int x;
    int *y;
};

#define FOO_INITIALIZER(name) \
{                             \
    .x = 1,                   \
    .y = &(name).x,           \
}

struct foo bar = FOO_INITIALIZER(bar);

This works in C99/C11 but what I really want is to drop the name parameter to the FOO_INITIALIZER macro. Is that possible?

I know this doesn't work:

#define FOO_INITIALIZER       \
{                             \
    .x = 1,                   \
    .y = &.x,                 \
}

If it is possible what section of ISO/IEC 9899:TC3 should I be looking in?

  • What about [`struct foo FOO_INITIALIZER(bar);`](https://ideone.com/e1LQjZ) – pmg Nov 28 '18 at 16:53
  • Very similar to above though it does have one benefit: not needing to put the name twice. It looks like that is the best that can be done with current C (or future C as I doubt WG14 will add self-referencing to the standard). – Nathan Hjelm Nov 28 '18 at 19:36

1 Answers1

1

There is no way to achieve what you want in the standard C language. You can either continue passing a name (but this does not work well for nested objects) or store offsets instead of pointers if this makes sense (highly dependent on the application) via offsetof.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • Thats what I thought. Thanks for confirming. Figured I would ask stackoverflow before I give up on the macro syntax I was after. – Nathan Hjelm Nov 28 '18 at 19:36