D (The Programming Language)/d2/Type Conversion
(Redirected from D (The Programming Language)/d2/Lesson 5)
Lesson 5: Type Conversion
editIn this lesson, you will learn how the types of variables can be implicitly and explicitly converted.
Introductory Code
editimport 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
editImplicit Integral Conversions
editAn 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:
bool
⇒ int
byte
⇒ int
ubyte
⇒ int
short
⇒ int
ushort
⇒ int
char
⇒ int
wchar
⇒ int
dchar
⇒ uint
Explicit Conversions
editCasting 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.