Adam Gausmann Adam Gausmann - 3 months ago 14
C Question

Assigning members of a const variable to another const

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?

Answer

This is because you are trying to initialize global variables at file scope, and at that scope only constants (foo.b is not) can be used to initialize values. My compiler gives a better message:

error: initializer element is not a compile-time constant
    .b = foo.b
         ~~~~^ 1 error generated.

If you had tried to do the same at block scope, that would have been correct:

typedef struct {
    int a;
    int b;
} aStruct;

int main() {
  const aStruct foo = {
    .a = 10,
    .b = 20
  };

  const aStruct bar = {
    .a = 15,
    .b = foo.b
  };
}

So, you'd better use some defines to initialize your global variables to the same value.

Comments