C initialize const struct element with existing constant variable

I use default C under gcc.

My code is:

typedef struct _OpcodeEntry OpcodeEntry; 

//

 struct _OpcodeEntry { unsigned char uOpcode; OpcodeMetadata pMetadata; }; 

//

 const OpcodeMetadata omCopyBytes1 = { 1, 1, 0, 0, 0, 0, &CopyBytes }; const OpcodeEntry pOpcodeTable[] = { { 0x0, omCopyBytes1 }, }; 

Errors:

 error: initializer element is not constant error: (near initialization for 'pOpcodeTable[0].pMetadata') 

If I changed omCopyBytes1 to what it actually installed in the line above, the code compiles fine. What am I doing wrong?

+6
source share
2 answers

You cannot use omCopyBytes1 to initialize the pOpcodeTable[] array member, because omCopyBytes1 is a variable that is constant at run time, and not a compile-time constant. Aggregate initializers in C must be compile-time constants, so the code from your post does not compile.

As a variable, omCopyBytes1 has its place in memory, which is initialized by an array of elements. You can use such a variable with a pointer, for example:

 struct _OpcodeEntry { unsigned char uOpcode; const OpcodeMetadata *pMetadata; }; ... const OpcodeEntry pOpcodeTable[] = { { 0x0, &omCopyBytes1 }, // This should work }; 

Alternatively, you can make this a preprocessor constant:

 #define omCopyBytes1 { 1, 1, 0, 0, 0, 0, &CopyBytes } 

If defined this way, omCopyBytes1 will no longer be a variable: it will be the definition of the preprocessor, which will disappear before the compiler is executed. I would recommend against the preprocessor method, but it is there if you must do this.

+5
source

In C, initializers for objects of static storage duration must be constant expressions. A const -qualified variable is not a constant expression.

0
source

All Articles