Variables in D Programming Language

Our first example will demonstrate variable declaration and initialization in D. Here’s the full source code:

import std.stdio;

void main()
{
    // `auto` declares a variable with type inference
    auto a = "initial";
    writeln(a);

    // You can declare multiple variables at once
    int b = 1, c = 2;
    writeln(b, " ", c);

    // D will infer the type of initialized variables
    auto d = true;
    writeln(d);

    // Variables declared without initialization are default-initialized
    // For integers, the default value is 0
    int e;
    writeln(e);

    // D doesn't have a specific shorthand for declaration and initialization
    // but you can use type inference with `auto`
    auto f = "apple";
    writeln(f);
}

To run the program, save the code in a file with a .d extension (e.g., variables.d) and use the D compiler (dmd) to compile and run it:

$ dmd -run variables.d
initial
1 2
true
0
apple

Let’s break down the key points:

  1. In D, variables can be explicitly declared with a type, or you can use auto for type inference.

  2. You can declare multiple variables of the same type in one line.

  3. D performs type inference when you use auto or initialize a variable.

  4. Variables declared without initialization are default-initialized. For integers, the default value is 0.

  5. D doesn’t have a specific shorthand syntax like := for declaration and initialization, but auto provides a concise way to declare and initialize variables with type inference.

  6. The writeln function from the std.stdio module is used for printing to the console.

Now that we’ve covered basic variable declaration and initialization in D, let’s move on to more language features.