-4

I'm getting a "error: initializer element is not constant" with this code:

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

const int a = 8;
const int b = 12;

my_struct test = { a, b };

Any idea of what's going on and how to fix it ?

Wolf
  • 9,679
  • 7
  • 62
  • 108
  • Note that this wouldn't be a problem if you initialized it inside a function instead (from C99 onwards). – vgru Nov 15 '17 at 14:38

2 Answers2

0

In C, using a const modifier does not produce a compile-time constant value.

Then, as per the rules of initialization, C11, chapter §6.7.9

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

you'll be needing a constant-expression (compile time constat).

You may use a #define MACRO instead to get the result you want. Something like (warning: Code not tested)

#include  <stdio.h>

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

//const int a = 8;
//const int b = 12;

#define a 8                  //use preprocessor MACROs
#define b 12                 //use preprocessor MACROs

my_struct test = { a, b };

int main(void)
{
    printf("Hello, world!\n");
    return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Besides macros (which have their downsides), unnamed enumerations are often used for the purpose to just provide compile-time constants. This would change your code like this.

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

enum {
    a = 8,
    b = 12, 
};

my_struct test = { a, b };

... also expressions involving compile-time constants can be compile-time constants themselves ...

my_struct test1 = { a+1, b };
my_struct test2 = { a, 'H' };

Also the sizeof operator can produce compile-time constants:

my_struct test3 = { sizeof(my_struct), b };

Even if this example looks not very useful, it compiles.

For learning what exactly constant expressions are, see for example Constant expressions - despite the URL (cppreference.com), this is the C reference part.

Wolf
  • 9,679
  • 7
  • 62
  • 108