Reputation: 9540
When looking at the initialization rules for aggregates in the N2310 I found the following paragraphs (emp. mine):
6.7.9(p19)
:
The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject; 154) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.
6.7.9(p21)
:
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
It seems to me that 6.7.9(p19)
implies 6.7.9(p21)
(but not wise versa). For instance:
#include <stdio.h>
struct test{
int a;
int b;
int c;
};
int main(){
struct test test = {
.a = 123
};
printf("%d%d%d\n", test.a, test.b, test.c); //obviously, 12300 is printed
}
I think this case can be explained by both 6.7.9(p19)
and 6.7.9(p21)
What is the purpose of 6.7.9(p21)
? What did I miss?
Upvotes: 2
Views: 95
Reputation: 311088
6.7.9 takes into account the so-called designated initializers.
Consider the following demonstrative program
#include <stdio.h>
struct test{
int a;
int b;
int c;
};
int main(void)
{
struct test test = {
.c = 123
};
printf("%d %d %d\n", test.a, test.b, test.c);
return 0;
}
Its output is
0 0 123
Or another program
#include <stdio.h>
int main(void)
{
enum { N = 10 };
int a[N] = { [0] = 0, [4] = 4, [9] = 9 };
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
putchar( '\n' );
return 0;
}
Its output is
0 0 0 0 4 0 0 0 0 9
So
all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.
The second quote existed before the designated initializers were adopted in the C Standard and describes the situation like for example this
char s[20] = "Hello";
and answers the question whether the tail of the character array will be initialized. It keeps the compatibility with the C++ Standard where the designated initializers were absent until the C++ 17 Standard.
Upvotes: 2