I want to add the value of a parameter to another parameter within a designated initializer, without having to define a separate variable to hold that value. Is this possible?
typedef struct {
int x;
int y;
} point;
int main() {
point p = {
.x = 1,
.y = x + 2 // I want to reference .x
};
}
This is not possible. The evaluation order of expressions in an initializer are not evaluated in any particular order, so there's no guarantee that .x
will be set to 1 before .y
is set to .x + 2
.
This is spelled out in section 6.7.9p23 of the C standard:
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)
Where footnote 152 states:
In particular, the evaluation order need not be the same as the order of subobject initialization.