Skip to content

Commit b3b668f

Browse files
committed
Fix Issue 21279 - cast expression between integer types is not defined
1 parent b20cf2f commit b3b668f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

spec/expression.dd

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1204,6 +1204,41 @@ $(H4 $(LNAME2 cast_static_array, Static Arrays))
12041204
---
12051205
)
12061206

1207+
$(H4 $(LNAME2 cast_integers, Integers))
1208+
1209+
$(P Casting an integer to a smaller integral will truncate the
1210+
value towards the least significant bits.
1211+
If the target type is signed and the most significant bit is set
1212+
after truncation, that bit will be lost from the value and
1213+
the sign bit will be set.)
1214+
1215+
$(SPEC_RUNNABLE_EXAMPLE_RUN
1216+
---
1217+
uint a = 260;
1218+
auto b = cast(ubyte) a;
1219+
assert(b == 4); // truncated like 260 & 0xff
1220+
1221+
int c = 128;
1222+
assert(cast(byte)c == -128); // reinterpreted
1223+
---
1224+
)
1225+
1226+
$(P Casting between signed and unsigned types will reinterpret the
1227+
value if the destination type cannot represent the source
1228+
value.)
1229+
1230+
$(SPEC_RUNNABLE_EXAMPLE_RUN
1231+
---
1232+
short c = -1;
1233+
auto d = cast(ushort) c;
1234+
assert(d == ushort.max);
1235+
1236+
ubyte e = 255;
1237+
auto f = cast(byte) e;
1238+
assert(f == -1);
1239+
---
1240+
)
1241+
12071242
$(H4 $(LNAME2 cast_floating, Floating Point))
12081243

12091244
$(P Casting a floating point literal from one type to another

0 commit comments

Comments
 (0)