Home > Blockchain >  Initialize constant from another constant with some changes
Initialize constant from another constant with some changes

Time:02-27

Let's say a have

struct table { int foo, bar, baz; };

static struct table const A = { .foo = 1, .bar = 2, .baz = 3 };

how could I declare B to be the exact same definition of A but with one change?

For instance what I would like to write is something like

static struct table const B = A, { .bar = 42 };

I am looking for a solution, if any, simpler than the following workaround:

#define A_DEFS .foo = 1, .bar = 2, .baz = 3
static struct table const A = { A_DEFS };

#define B_DEFS A_DEFS, .bar = 42
static struct table const B = { B_DEFS };

CodePudding user response:

Try :

static struct table const B = {  A.foo, .bar = 42, A.baz };

CodePudding user response:

SparKot's answer let me come to this slightly more convenient solution:

struct table { int foo, bar, baz; };
#define BASE(X) X.foo, X.bar, X.baz

static struct table const A = { .foo = 1, .bar = 2, .baz = 3 };
static struct table const B = { BASE(A), .bar = 42 };
static struct table const C = { BASE(B), .baz = 24 };
  •  Tags:  
  • c
  • Related