Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Basics and Types

Type Conversion and Casting in D

Learn which conversions D performs automatically, how integer promotion works, when to use std.conv.to for safe conversions, and when a cast is needed and dangerous.

Programs constantly change a value from one type to another: a text field into an integer, an int into a double, a long into a ubyte. D has three levels of conversion. Some are automatic and safe, some are explicit and checked, and some are explicit and unchecked. Knowing which is which prevents the silent truncation bugs of C. All D code here is read-only; the C stand-ins demonstrate the underlying bit behavior.

Implicit conversions

D converts automatically when no information can be lost:

D
byte b = 5;
int i = b;          // ok: byte widens to int
long l = i;         // ok
double d = i;       // ok: int to double is exact
float f = 3;        // ok: constant 3 fits

It refuses when information could be lost:

D
int big = 300;
// ubyte small = big;        // Error: cannot implicitly convert int to ubyte
// int n = 3.7;              // Error: cannot implicitly convert double to int
ubyte ok = 200;              // ok: the compiler sees the constant fits

D tracks value ranges for expressions as well: ubyte c = a & 0x0F; compiles when a is a ubyte because the result can only be 0 to 15. This makes many narrowing conversions work without casts when they are provably safe.

Integer promotion

Arithmetic on small integers happens in int. The operands byte, ubyte, short, ushort, char and bool are promoted to int first, so the result of adding two ubyte values is an int:

D
ubyte x = 200, y = 100;
auto z = x + y;          // int, value 300
// ubyte w = x + y;      // Error: 300 does not fit
ubyte w = cast(ubyte)(x + y);   // 44: explicit wrap

When a signed and an unsigned operand of the same size meet, the signed one is converted to unsigned. That is a famous source of surprises:

D
int  a = -1;
uint u = 1;
writeln(a < u);          // false! a becomes 4294967295

D accepts this to stay compatible with C-style arithmetic, so prefer using one signedness consistently and be careful with .length, which is unsigned (size_t).

Safe conversion with std.conv.to

to!T(value) converts between types with checks. It parses text, converts numbers, and throws an exception when the value does not fit:

D
import std.conv : to, ConvException, ConvOverflowException;
import std.stdio;

void main()
{
    writeln("123".to!int + 1);       // 124
    writeln(3.99.to!int);            // 3 (truncates toward zero)
    writeln(65.to!char);             // A
    writeln(255.to!ubyte);           // 255
    writeln(42.to!string);           // 42
    writeln("3.5".to!double);        // 3.5

    try
    {
        auto v = 300.to!ubyte;       // does not fit
    }
    catch (ConvOverflowException e)
    {
        writeln("overflow caught");
    }

    try
    {
        auto v = "12x".to!int;
    }
    catch (ConvException e)
    {
        writeln("not a number");
    }
}

to is the right tool for user input, files and any value you did not compute yourself. For floating-point to integer, to!int truncates; use std.math.round or lrint first if you want rounding.

cast: explicit and unchecked

cast(T)expr forces a conversion and does not check it:

D
int n = 321;
ubyte low = cast(ubyte) n;          // 65: keeps the low 8 bits
double d = 9.99;
int t = cast(int) d;                // 9

Casts between unrelated class types are checked at run time (cast(Derived) base yields null when wrong), but numeric and pointer casts are not. Reserve cast for places where you have proven the value is in range, and prefer to!T everywhere else. D also has special casts to remove qualifiers, such as cast()value (drop all top-level qualifiers) and cast(const), which are discussed in the memory chapter.

Conversions in conditions

D does not treat any integer as a bool implicitly in a variable assignment (bool ok = 5; works as true but is flagged by style checkers), but if (n) tests non-zero and if (ptr) tests non-null. Writing if (n != 0) is clearer.

C stand-ins: truncation and promotion

C C stand-in: cast to ubyte keeps the low bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output is 321 as ubyte: 65, 9.99 as int: 9, 200 + 100 = 300 and wrapped: 44. These match the D examples above.

C C stand-in: the signed/unsigned comparison trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You will see 0 for the naive comparison, 1 after converting the unsigned value, and (unsigned)a = 4294967295. The compiler may warn about the first comparison. D has the same promotion rule, so the same trap exists there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which line does D reject without a cast?

    Converting a double to int can lose information, so it needs an explicit conversion.
  2. 2. What is the type of ubyte + ubyte in D?

    Small integers are promoted to int in arithmetic.
  3. 3. What does "12x".to!int do?

    to checks the whole string and throws on invalid input.
  4. 4. What is cast(ubyte) 321?

    The cast keeps the low 8 bits: 321 mod 256 is 65.

Summary

  • D converts implicitly only when no information is lost, using value-range tracking.
  • Small integers are promoted to int; mixing signed and unsigned can surprise you.
  • std.conv.to!T converts with checks and throws on failure; use it for input.
  • cast is explicit and unchecked for numbers: use it only when you are sure.

Next: Operators and expressions