Skip to content

Commit 8e7598f

Browse files
committed
[spec/type] Improve numeric type conversion examples
Move integer promotion examples to that section and show dchar promotion. Add rationale for integer promotion. Add rationale for numeric type conversion rules. Rename int, uint variables for signed/unsigned example and show long/ulong. Add floating point example.
1 parent 7d00668 commit 8e7598f

File tree

1 file changed

+42
-11
lines changed

1 file changed

+42
-11
lines changed

spec/type.dd

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,28 @@ $(H3 $(LEGACY_LNAME2 Integer Promotions, integer-promotions, Integer Promotions)
274274
column.
275275
)
276276

277+
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
278+
---
279+
byte a;
280+
auto b = a + a;
281+
static assert(is(typeof(b) == int));
282+
// error: can't implicitly convert expression of type int to byte:
283+
//byte c = a + a;
284+
285+
ushort d;
286+
// error: can't implicitly convert expression of type int to ushort:
287+
//d = d * d;
288+
int e = d * d; // OK
289+
static assert(is(typeof(int() * d) == int));
290+
291+
dchar f;
292+
static assert(is(typeof(f - f) == uint));
293+
---
294+
)
295+
296+
$(RATIONALE 32-bit integer operations are often faster than smaller integers
297+
for single variables on modern architectures.)
298+
277299
$(H3 $(LEGACY_LNAME2 Usual Arithmetic Conversions, usual-arithmetic-conversions, Usual Arithmetic Conversions))
278300

279301
$(P The usual arithmetic conversions convert operands of binary
@@ -310,21 +332,30 @@ $(H3 $(LEGACY_LNAME2 Usual Arithmetic Conversions, usual-arithmetic-conversions,
310332
)
311333
)
312334

335+
$(RATIONALE The above rules follow C99, which makes porting code from C easier.)
336+
337+
$(P $(B Example:) Signed and unsigned conversions:)
313338
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
314339
---
315-
byte a;
316-
int b = a * a;
317-
auto c = a + a;
318-
static assert(is(typeof(c) == int));
340+
int i;
341+
uint u;
342+
static assert(is(typeof(i + u) == uint));
343+
static assert(is(typeof(short() + u) == uint));
344+
static assert(is(typeof(ulong() + i) == ulong));
345+
static assert(is(typeof(long() - u) == long));
346+
static assert(is(typeof(long() * ulong()) == ulong));
347+
---
348+
)
319349

320-
ushort d;
321-
static assert(is(typeof(b * d) == int));
350+
$(P $(B Example:) Floating point:)
351+
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
352+
---
353+
float f;
354+
static assert(is(typeof(f + ulong()) == float));
322355

323-
uint e;
324-
static assert(is(typeof(b + e) == uint));
325-
static assert(is(typeof(d + e) == uint));
326-
static assert(is(typeof(ulong() + b) == ulong));
327-
static assert(is(typeof(long() - e) == long));
356+
double d;
357+
static assert(is(typeof(f * d) == double));
358+
static assert(is(typeof(real() / d) == real));
328359
---
329360
)
330361

0 commit comments

Comments
 (0)