初始化const的结构体与其他const的结构体实例 [英] Initializing Const Struct with other Const Struct Instances

查看:3992
本文介绍了初始化const的结构体与其他const的结构体实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,为什么下面的code段不能编译:

I'm curious why the following code snippet doesn't compile:

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

static const Foo FooZero = { 0, 0 };

typedef struct Bar {
    Foo foo;
    int c;
} Bar;

static const Bar BarZero = { FooZero, 0 };

据抱怨使用 FooZero ,指出 FooZero 不是编译时常

但是,是不是?什么是我不理解吗?

But isn't it? What am I not understanding here?

很显然,我可以简单地用替换初始使用 FooZero {0,0} - 我的目的问​​这个问题是不是怎么去解决这个问题 - 我想了解原故 FooZero 不是,事实上,编译时间常数。

Obviously, I can simply replace the use of FooZero in the initializer with { 0, 0 } - my purpose in asking the question is not how to get around the problem - I'm trying to understand the underlying reason why FooZero is not, in fact, a compile-time constant.

感谢

推荐答案

它主要做初始化。

初​​始化的变量通常不是由code它说把这个值到该位置初始化,但由加载特定的值范围内的定义,。数据 RESP。 .RODATA 段,到它应该是内存位置。这是由OS文件装载完成。 (严格地说,这不是C,它不知道任何东西的属性,但执行环境)。

The initialized variables are usually not initialized by code which says "put this value to that location", but by a definition which loads a specific value range, the .data resp. .rodata segment, to the memory location where it is supposed to be. This is done by the OS file loader. (Strictly speaking, this is not a property of C, which doesn't know anything about that, but of the execution environment.)

这就是说,它是不可能告诉该存储区的一部分,从另一个被复制。但是,TE编译itselfs识别声明的意图,并把相同的值来diefferent地点将有可能。但是,这很可能是太多猜测。

That said, it is not possible to tell a part of this memory area to be copied from another one. But it would be possible that te compiler itselfs recognizes the intent of the declaration and puts the same values to diefferent locations. But that would probably be too much "guessing".

在你的情况:会不会一个指向 FooZero 也许是更好的解决方案?的值均为同一...

In your case: Wouldn't a pointer to FooZero maybe a better solution? The values are both the same...

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

static const Foo FooZero = { 0, 0 };

typedef struct Bar {
    Foo * foo;
    int c;
} Bar;

static const Bar BarZero = { &FooZero, 0 };

或圆形的其他方式:

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

typedef struct Bar {
    Foo foo;
    int c;
} Bar;

static const Bar BarZero = { { 0, 0 }, 0 };
static const Foo * FooZero = &BarZero.foo; // if that is possible, untested...

在第一种情况下,你必须访问 BarZero.foo 的组件与 - > (像 BarZero.foo->将),

In the first case, you would have to access BarZero.foo's components with -> (like BarZero.foo->a),

在第二种情况下,你必须访问 FooZero 的组件与 - > (如 FooZero-方式> A

in the second case you would have to access FooZero's components with -> (like FooZero->a).

这篇关于初始化const的结构体与其他const的结构体实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆