An attempt to use designated initializers to explicitly re-initialize
a sub-member `y` of a struct member `b.a`
#include <stdio.h>
struct A { int x, y; };
struct B { struct A a; };
int main(void)
{
struct A ia = { 1, 2 };
struct B b = { .a = ia, .a.y = 42 };
printf("%d %d\n", b.a.x, b.a.y);
}
GCC outputs:
0 42
I.e. it does initialize `b.a.y` with `42`, but for some reason also
produces zero in `b.a.x`. Meanwhile, Clang, MSVC output
1 42
as expected.
The funny part is that this exact functionality is actually directly illustrated by the standard in "6.7.11 Initialization" example 12.
Is it just a bug or is there some defiant reasoning (e.g. "we know
better") for GCC's behavior?
Are you sure about MSVC?
I tested both with VS2017 and with VS2022. Both printed '0 42'.
[...]
Is it just a bug or is there some defiant reasoning (e.g. "we know
better") for GCC's behavior?
On Wed 9/10/2025 7:45 AM, Michael S wrote:
Are you sure about MSVC?
I tested both with VS2017 and with VS2022. Both printed '0 42'.
I simply tried it on whatever was currently installed on my machine,
without giving it too much thought, and it printed `1 42` right away.
It is VS2022.
Just checked the version. It identifies itself as "Version 17.14.6
(June 2025)".
My guess is that you compile from VS GUI and that your GUI configured
to use clang/LLVM tools instead of MSVC.
* Andrey Tarasevich <noone@noone.net> in comp.lang.c:
[...]
Is it just a bug or is there some defiant reasoning (e.g. "we know
better") for GCC's behavior?
Indeed, I found this which seems to confirm: https://stackoverflow.com/questions/40920714/is-full-followed-by-partial-initialization-of-a-subobject-undefined-behavior
(but I could't find anything in gcc bugzilla)
An attempt to use designated initializers to explicitly re-initialize a sub-member `y` of a struct member `b.a`
#include <stdio.h>
struct A { int x, y; };
struct B { struct A a; };
int main(void)
{
struct A ia = { 1, 2 };
struct B b = { .a = ia, .a.y = 42 };
printf("%d %d\n", b.a.x, b.a.y);
}
GCC outputs:
0 42
I.e. it does initialize `b.a.y` with `42`, but for some reason also
produces zero in `b.a.x`. Meanwhile, Clang, MSVC output
1 42
as expected.
Sysop: | DaiTengu |
---|---|
Location: | Appleton, WI |
Users: | 1,069 |
Nodes: | 10 (0 / 10) |
Uptime: | 70:55:40 |
Calls: | 13,725 |
Files: | 186,960 |
D/L today: |
4,358 files (1,099M bytes) |
Messages: | 2,410,344 |