I'm trying to define two const variables with the same data structure. I want to ensure that all of the members of each variable are exactly the same except for the one that I am changing. Since I do not want to maintain two exact copies of the same code, I thought "why not use the existing members in one to initialize the other?"
Here is an example in code:
typedef struct {
int a;
int b;
} aStruct;
const aStruct foo = {
.a = 10,
.b = 20
};
const aStruct bar = {
.a = 15,
.b = foo.b
};
When I try to compile this code, I get an error:
foo.c:13:14: error: initializer element is not constant
.b = foo.b
^~~
foo.c:13:14: note: (near initialization for ‘bar.b’)
I'm fairly new to C, so I don't fully understand how constants and data structures work, especially when they are put together. Can someone help me figure out what is going on here?