简体   繁体   English

C用现有的const变量初始化const struct成员

[英]C initialize const struct member with existing const variable

I'm using default C under gcc. 我在gcc下使用默认的C语言。

My code: 我的代码:

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 change omCopyBytes1 to what it's actually set to in the above line, the code compiles fine. 如果我将omCopyBytes1更改为它在上面的行中实际设置的内容,则代码编译正常。 What am I doing wrong? 我究竟做错了什么?

You cannot use omCopyBytes1 to initialize a member of pOpcodeTable[] array, because omCopyBytes1 is a variable that is run-time constant, not a compile-time constant. 您不能使用omCopyBytes1初始化pOpcodeTable[]数组的成员,因为omCopyBytes1是一个运行omCopyBytes1量的变量,而不是编译时常量。 Aggregate initializers in C must be compile-time constants, that's why the code from your post does not compile. C中的聚合初始值设定项必须是编译时常量,这就是你的帖子中的代码无法编译的原因。

As a variable, omCopyBytes1 has its own place in memory, which is initialized to an array of items. 作为变量, omCopyBytes1在内存中有自己的位置,它被初始化为一个项目数组。 You can use such variable by a pointer, like this: 您可以通过指针使用此类变量,如下所示:

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

Alternatively, you can make it a preprocessor constant: 或者,您可以使其成为预处理器常量:

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

If defined in this way, the omCopyBytes1 would no longer be a variable: it would be a preprocessor definition that vanishes before the compiler is done. 如果以这种方式定义, omCopyBytes1将不再是变量:它将是在编译器完成之前消失的预处理器定义。 I would recommend against the preprocessor method, but it's there in case you must do it. 我建议不要使用预处理器方法,但是如果你必须这样做的话。

In C, initializers for objects of static storage duration must be constant expressions . 在C中,静态存储持续时间对象的初始化程序必须是常量表达式 A const -qualified variable is not a constant expression. const -qualified变量不是常量表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM