如何在指定的初始化程序中引用参数?
How can I reference a parameter within a designated initializer?
我想将一个参数的值添加到指定初始值设定项中的另一个参数,而无需定义单独的变量来保存该值。这可能吗?
typedef struct {
int x;
int y;
} point;
int main() {
point p = {
.x = 1,
.y = x + 2 // I want to reference .x
};
}
这是不可能的。初始化器中表达式的求值顺序不会以任何特定顺序求值,因此无法保证 .x
会在 .y
设置为 .x + 2
.[=16= 之前设置为 1 ]
这在 C standard 的第 6.7.9p23 节中有详细说明:
The evaluations of the initialization list expressions are
indeterminately sequenced with respect to one another and
thus the order in which any side effects occur is
unspecified.152)
脚注 152 指出:
In particular, the evaluation order need not be the same as the order
of subobject initialization.
我想将一个参数的值添加到指定初始值设定项中的另一个参数,而无需定义单独的变量来保存该值。这可能吗?
typedef struct {
int x;
int y;
} point;
int main() {
point p = {
.x = 1,
.y = x + 2 // I want to reference .x
};
}
这是不可能的。初始化器中表达式的求值顺序不会以任何特定顺序求值,因此无法保证 .x
会在 .y
设置为 .x + 2
.[=16= 之前设置为 1 ]
这在 C standard 的第 6.7.9p23 节中有详细说明:
The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and
thus the order in which any side effects occur is unspecified.152)
脚注 152 指出:
In particular, the evaluation order need not be the same as the order of subobject initialization.