Variables, Types and Literals

4.1 Declaring Variables

Every variable is default-initialized with its type's .init value (int → 0, float → NaN, char → 0xFF, references → null).

Opt out with = void for performance: int[1024] buf = void;.

int count = 0;
auto name = "D";             // type inference (string)
double pi = 3.14159;
int a, b = 5, c;             // a and c default-initialized
const int limit = 10;        // can't be modified through this reference
immutable int forever = 42;  // never changes (anywhere)
enum answer = 42;            // manifest constant (compile-time, no storage)

4.2 Basic Types

byte, short, int, long, (cent reserved) 8, 16, 32, 64 bits ubyte, ushort, uint, ulong

float, double, real (largest hardware float, 80-bit on x86) 32, 64, 80+ bits

char (UTF-8 code unit), wchar (UTF-16), dchar (UTF-32) 8, 16, 32 bits

void, size_t / ptrdiff_t (aliases), typeof(null) Integer sizes are fixed on all platforms (int is always 32-bit, long always 64-bit).

4.3 Type Properties

writeln(int.max, " ", int.min, " ", int.sizeof, " ", int.init);
writeln(double.nan, " ", double.infinity, " ", double.epsilon, " ", float.dig);
writeln(typeof(3.0).stringof);   // "double"

4.4 Literals

auto dec = 1_000_000;
auto hex = 0xFF;
auto bin = 0b1010;
auto oct = std.conv.octal!755;   // no 0-prefix octals
auto l = 42L;
auto u = 42u;
auto ul = 42UL;
auto f = 1.5f;
auto d = 1.5;
auto r = 1.5L;                   // real
auto e = 6.02e23;
auto c = 'A';
auto s = "string";
auto ws = "wide"w;               // wstring
auto ds = "dchars"d;             // dstring
auto raw = r"C:\no\escapes";
auto wys = `also raw`;
auto hexStr = x"48 65 6C 6C 6F"; // "Hello"
auto delim = q"(delimited "string")";
auto heredoc = q"EOS
multi-line
heredoc
EOS";
auto tokenStr = q{ int x = 5; }; // token string (must be valid D tokens; used with mixins)
auto interp = i"Hello $(name)";  // interpolated expression sequence (2.108+)

4.5 Type Conversions

Implicit narrowing isn't allowed (except value range propagation: ubyte b = x & 0xFF; is fine).

import std.conv : to;
int i = 42;
long l = i;                       // implicit widening
int back = cast(int) l;           // explicit cast
double d = i;                     // implicit int → double
string s = i.to!string;           // "42"
int parsed = "123".to!int;        // throws ConvException on bad input
float f = "3.14".to!float;
auto clamped = 300.to!ubyte;      // throws ConvOverflowException
ubyte b = cast(ubyte) 300;        // truncates (44)