diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 5c0e3b30b76e329c53a6ae11512b347b5291eec8..dd78de3cc884c5357ea55deb848488f0babafb8b 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -308,9 +308,7 @@ pub fn zeroes(comptime T: type) T { if (comptime meta.containerLayout(T) == .Extern) { // The C language specification states that (global) unions // should be zero initialized to the first named member. - var item: T = undefined; - @field(item, info.fields[0].name) = zeroes(@TypeOf(@field(item, info.fields[0].name))); - return item; + return @unionInit(T, info.fields[0].name, zeroes(info.fields[0].field_type)); } @compileError("Can't set a " ++ @typeName(T) ++ " to zero."); @@ -416,6 +414,9 @@ test "mem.zeroes" { var c = zeroes(C_union); try testing.expectEqual(@as(u8, 0), c.a); + + comptime var comptime_union = zeroes(C_union); + try testing.expectEqual(@as(u8, 0), comptime_union.a); } /// Initializes all fields of the struct with their default value, or zero values if no default value is present. diff --git a/test/run_translated_c.zig b/test/run_translated_c.zig index 80e889b44ce84abd07b9d85f9663e55410640d9f..933cf54c4f6aea8986ae9dc4ca2cb592d1aae73d 100644 --- a/test/run_translated_c.zig +++ b/test/run_translated_c.zig @@ -1819,4 +1819,14 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void { \\ return 0; \\} , ""); + + cases.add("Zero-initialization of global union. Issue #10797", + \\#include + \\union U { int x; double y; }; + \\union U u; + \\int main(void) { + \\ if (u.x != 0) abort(); + \\ return 0; + \\} + , ""); }