D (The Programming Language)/d2/Type Conversion

Lesson 5: Type Conversion Edit

In this lesson, you will learn how the types of variables can be implicitly and explicitly converted.

Introductory Code Edit

import std.stdio;
void main()
    short a = 10;
    int b = a;
    // short c = b;
    // Error:  cannot implicitly convert 
    // expression b of type int to short
    short c = cast(short)b;
    char d = 'd';
    byte e = 100;
    wchar dw = 'd';
    int f = d + e + dw;
    writeln(f); //300
    float g1 = 3.3;
    float g2 = 3.3;
    float g3 = 3.4;
    int h = cast(int)(g1 + g2 + g3);
    writeln(h); //10
    int i = cast(int)g1 + cast(int)g2 + cast(int)g3;
    writeln(i); //9

Concepts Edit

Implicit Integral Conversions Edit

An object of an integral type can be converted to another object of an integral type as long as the destination type is wider than the original type. These conversions are implicit:


Explicit Conversions Edit

Casting is a way to tell the compiler to try to force an object to change type. In D, you do this by writing cast(type).

Tips Edit

  • You cannot convert an integral value to a string (or the other way around) with a cast. There is a library function which you will learn later for that.