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:

boolint
byteint
ubyteint
shortint
ushortint
charint
wcharint
dcharuint

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.