Chuyển đến nội dung

Bài 5 · Basics and Types

Variables, Types and Initialization in D

Learn how D declares variables, how default initialization works, how auto infers types, and what const, immutable and enum mean for values that never change.

A variable is a named place to keep a value, and D's rules for declaring one are designed to avoid the classic C bugs. Every variable has a static type fixed at compile time, and every variable is initialized: if you do not give a value, D uses the type's default. This lesson covers the built-in types, auto, the .init and .sizeof properties, and the three ways to say "this does not change": const, immutable and enum.

Declaring variables

D
import std.stdio;

void main()
{
    int count = 10;
    double ratio = 0.75;
    bool ready = true;
    char letter = 'D';
    string title = "Learning D";

    int missing;                 // no initializer: gets int.init, which is 0
    writeln(count, " ", ratio, " ", ready, " ", letter, " ", title);
    writeln(missing);            // 0
}

The syntax is Type name = value;. The first line of output is 10 0.75 true D Learning D, and the second is 0.

Basic types and their default values

Type Size Default (.init)
bool 8 bits false
byte / ubyte 8 bits 0
short / ushort 16 bits 0
int / uint 32 bits 0
long / ulong 64 bits 0
float 32 bits float.nan
double 64 bits double.nan
char 8 bits (UTF-8 unit) 0xFF
wchar / dchar 16 / 32 bits 0xFFFF / 0x0000FFFF

Unlike C, sizes are fixed by the language: an int is always 32 bits and a long always 64, on every platform. Floating-point variables start as nan ("not a number"), not zero. That is deliberate: if you forget to set a double, the NaN spreads through your results and makes the mistake visible instead of quietly using zero. Every type has .init, .sizeof, and numeric types have .min and .max:

D
import std.stdio;

void main()
{
    writeln(int.sizeof, " ", long.sizeof);   // 4 8
    writeln(int.max);                         // 2147483647
    writeln(ubyte.max);                       // 255
    double d;
    writeln(d);                               // nan
    writeln(typeof(d).stringof);              // double
}

Type inference with auto

auto lets the compiler deduce the type from the initializer. It does not make D dynamic: the type is still fixed, just not written.

D
auto n = 5;          // int
auto x = 2.5;        // double
auto s = "hello";    // string (immutable(char)[])
auto big = 5_000_000_000;   // long: the literal does not fit in int
auto f = 1.5f;       // float

Underscores in number literals are allowed for readability (1_000_000), and prefixes pick bases: 0xFF is hexadecimal and 0b1010 is binary. Octal has no prefix; use octal!17 from std.conv. auto shines with long types such as ranges, and in foreach loops where the compiler works out the element type.

const, immutable and enum

D
import std.stdio;

void main()
{
    immutable int daysInWeek = 7;       // never changes, guaranteed
    const double taxRate = 0.2;         // read-only through this name
    enum maxUsers = 100;                // a compile-time constant

    int[maxUsers > 50 ? 4 : 2] table;   // enum can be used where a constant is needed
    writeln(table.length);              // 4
    // daysInWeek = 8;                  // Error: cannot modify immutable
}

How they differ:

  • immutable data can never change through any reference. The compiler may share it freely between threads.
  • const means "I will not change it through this reference", but another mutable name for the same data could still change it.
  • enum creates a manifest constant: a name for a value known at compile time, which is replaced wherever it is used and takes no storage. Enums are also how D defines named sets of values (covered in Operators and expressions).

Prefer immutable or enum for true constants; reserve const for parameters where you promise not to modify a caller's data.

Scope and shadowing

A variable lives until the end of its block. D also rejects a local that hides another local in an enclosing scope of the same function, so an accidental duplicate name is an error, not a silent bug.

Stand-ins for default values and sizes

A C program can mirror D's fixed-size types with <stdint.h>, and it can show why D's NaN default is useful.

C C stand-in: fixed-size types like D's int and long

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.

It prints sizes 4 and 8, the maximum 2147483647, 255 and 5000000. These are exactly D's int.sizeof, long.sizeof, int.max and ubyte.max.

C C stand-in: why a NaN default catches mistakes

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 result is nan, and isnan reports 1. In D, a forgotten double produces this visible NaN; in C an uninitialized local holds garbage that often looks like a plausible number.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is the default value of an uninitialized double in D?

    Floating-point types default to NaN so forgotten initializations are visible.
  2. 2. How many bits is a D int on every platform?

    D fixes the sizes of its integer types.
  3. 3. Which keyword creates a compile-time constant that takes no storage?

    An enum manifest constant is substituted at compile time.
  4. 4. What does auto do in auto x = 2.5;?

    auto infers the type; it stays static.

Summary

  • Every variable is initialized: integers to 0, floats to NaN, bool to false.
  • Integer sizes are fixed (int 32 bits, long 64 bits).
  • auto infers a static type; immutable, const and enum express constants of different strength.
  • Use .init, .sizeof, .min and .max to inspect types.

Next: Integers and floating-point numbers

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.