Skip to content

Commit 2f83582

Browse files
authored
Merge pull request #3373 from ntrel/cast-int
Fix Issue 21279 - cast expression between integer types is not defined Signed-off-by: Dennis <[email protected]> Merged-on-behalf-of: Dennis <[email protected]>
2 parents d05e534 + bf393e2 commit 2f83582

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

spec/expression.dd

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -697,7 +697,7 @@ $(H3 $(LNAME2 integer_comparisons, Integer Comparisons))
697697
$(P It is an error to have one operand be signed and the other
698698
unsigned for a $(D <), $(D <)$(D =), $(D >) or
699699
$(D >)$(D =) expression.
700-
Use casts to make both operands signed or both operands unsigned.
700+
Use $(RELATIVE_LINK2 cast_integers, casts) to make both operands signed or both operands unsigned.
701701
)
702702

703703
$(H3 $(LEGACY_LNAME2 floating_point_comparisons, floating-point-comparisons, Floating Point Comparisons))
@@ -1173,6 +1173,43 @@ $(H4 $(LNAME2 cast_static_array, Static Arrays))
11731173
---
11741174
)
11751175

1176+
$(H4 $(LNAME2 cast_integers, Integers))
1177+
1178+
$(P Casting an integer to a smaller integral will truncate the
1179+
value towards the least significant bits.
1180+
If the target type is signed and the most significant bit is set
1181+
after truncation, that bit will be lost from the value and
1182+
the sign bit will be set.)
1183+
1184+
$(SPEC_RUNNABLE_EXAMPLE_RUN
1185+
---
1186+
uint a = 260;
1187+
auto b = cast(ubyte) a;
1188+
assert(b == 4); // truncated like 260 & 0xff
1189+
1190+
int c = 128;
1191+
assert(cast(byte)c == -128); // reinterpreted
1192+
---
1193+
)
1194+
1195+
$(P Converting between signed and unsigned types will reinterpret the
1196+
value if the destination type cannot represent the source
1197+
value.)
1198+
1199+
$(SPEC_RUNNABLE_EXAMPLE_RUN
1200+
---
1201+
short c = -1;
1202+
ushort d = c;
1203+
assert(d == ushort.max);
1204+
assert(uint(c) == uint.max);
1205+
1206+
ubyte e = 255;
1207+
byte f = e;
1208+
assert(f == -1); // reinterpreted
1209+
assert(short(e) == 255); // no change
1210+
---
1211+
)
1212+
11761213
$(H4 $(LNAME2 cast_floating, Floating Point))
11771214

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

0 commit comments

Comments
 (0)