Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign constant values to structs in C

Tags:

c

constants

This is an array of structs with elements declared as const.
It is also passed as global in the header file using extern keyword.

// foo.h file
typedef enum
{
    A = 0,
    B,
    C,
    NAMES_MAX,
} Names_t;

typedef struct
{
    const int x;
    const int y;
} Foot_t;

// my global array.
extern const Foot_t FOO[NAMES_MAX];
// foo.c file
const Foot_t FOO[NAMES_MAX] =
{
    [A] = { .x = 1, .y = 1 },
    [B] = { .x = 2, .y = 2 },
    [C] = { .x = 3, .y = 3 },
};

I use the Names_t as index for the struct FOO.

Now I tried to use my global struct to assign a value to another struct.

// bar.c file
typedef struct
{
    const int x;
    const int y;
    // more members here.
} Bar_t;

static Bar_t BAR =
{
    .x = FOO[A].x,
    .y = FOO[A].y,
};

But I get an error initializer element is not constant in C.
I know what the error means, FOO is not actually a constant expression as it would be in C++.

The question is how can I resolve this error by maintain the structure above?

like image 571
blinkbetter Avatar asked Oct 12 '25 11:10

blinkbetter


1 Answers

Objects either declared at file scope or with the keyword static, i.e. those with static storage duration, must be initialized with a constant expression, and the value of another value (whether or not it is declared const) is not such an expression. You'll need to initialize the values explicitly.

Also, it's not a good idea to declare members of a struct as const. It can cause issues when you attempt to use the struct. You're better off declaring specific instances as const rather than the members, i.e.:

typedef struct
{
  int x;
  int y;
}Foot_t;

const Foot_t FOO[NAMES_MAX] =
{
  [A] = { .x = 1, .y = 1},
  [B] = { .x = 2, .y = 2},
  [C] = { .x = 3, .y = 3},
};
like image 159
dbush Avatar answered Oct 14 '25 07:10

dbush