What is the expected behavior of referring to previously set fields, when declaring initial values for a struct using compound literal: Specifically is it ok to: struct foo v = { .v1 = ..., .v2 = .v1+1 };
More complete example:
struct s {
int i1 ;
int i2 ;
} ;
void func(void)
{
struct s v1 = { 3 } ;
v1 = (struct s) ( .i1 = 4, .i2 = v1.i1+10 }
// always v1.i2=13, NOT 14
// Is this legal ?
struct s v2 = ( .i1 = 1, .i2 = v2.i1+10 }
// Under GCC, v2.i2 = 11
}
The first case – the standard is clear that “temporary” compound literal is created, based on the value of v1 before the assignment (v1.i1=3), resulting in v2.i2 = 13. The explanation is that this is basically:
struct s v1 = { 3 } ;
struct s temp = ( .i1 = 4, .i2 = v1.i1+10 }
v1 = temp ;
For the second case, at least with GCC, it looks as if it’s OK to reference previously set values in the SAME statement – in this case i2 is set to 11, implying that this was NOT implemented using temporary variable which would have results in v2.i2 = 10;
struct s temp = ( .i1 = 4, .i2 = v1.i1+10 }
struct s v1 = temp ;
My question: what does the C99/C23 standard says about the second case ? is it required behavior, implementation specific behavior or undefined behavior which compilers should flag as warning/error ?
I tried the above with GCC9 (-Wall, -Wextra), also with Coverity – no issue was raises.