mirror of
https://github.com/ziglang/zig.git
synced 2024-11-26 23:22:44 +00:00
std: Allow mem.zeroes
to work at comptime with extern union
Fixes #10797
This commit is contained in:
parent
435beb4e1d
commit
e382e7be2b
@ -309,9 +309,7 @@ pub fn zeroes(comptime T: type) T {
|
|||||||
if (comptime meta.containerLayout(T) == .Extern) {
|
if (comptime meta.containerLayout(T) == .Extern) {
|
||||||
// The C language specification states that (global) unions
|
// The C language specification states that (global) unions
|
||||||
// should be zero initialized to the first named member.
|
// should be zero initialized to the first named member.
|
||||||
var item: T = undefined;
|
return @unionInit(T, info.fields[0].name, zeroes(info.fields[0].field_type));
|
||||||
@field(item, info.fields[0].name) = zeroes(@TypeOf(@field(item, info.fields[0].name)));
|
|
||||||
return item;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
|
@compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
|
||||||
@ -417,6 +415,9 @@ test "mem.zeroes" {
|
|||||||
|
|
||||||
var c = zeroes(C_union);
|
var c = zeroes(C_union);
|
||||||
try testing.expectEqual(@as(u8, 0), c.a);
|
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.
|
/// Initializes all fields of the struct with their default value, or zero values if no default value is present.
|
||||||
|
@ -1819,4 +1819,14 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
|
|||||||
\\ return 0;
|
\\ return 0;
|
||||||
\\}
|
\\}
|
||||||
, "");
|
, "");
|
||||||
|
|
||||||
|
cases.add("Zero-initialization of global union. Issue #10797",
|
||||||
|
\\#include <stdlib.h>
|
||||||
|
\\union U { int x; double y; };
|
||||||
|
\\union U u;
|
||||||
|
\\int main(void) {
|
||||||
|
\\ if (u.x != 0) abort();
|
||||||
|
\\ return 0;
|
||||||
|
\\}
|
||||||
|
, "");
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user