D (The Programming Language)/d2/Types and Declaration

From Wikibooks, open books for an open world
Jump to: navigation, search

Lesson 2: Types and Declarations[edit]

In this lesson, you will learn how to declare and use variables.

Introductory Code[edit]

The Basic Declaring of Variables[edit]

import std.stdio;
 
int b;
 
void main()
{
    b = 10;
    writeln(b);  // prints 10
    int c = 11;
    // int c = 12;  Error: declaration c is already defined
 
    string a = "this is a string";
    writeln(a);  // prints this is a string
 
    // a = 1;  Error, you can't assign an int to a string variable
 
    int d, e, f;  // declaring multiple variables is allowed
}

Manipulation of Variables[edit]

import std.stdio;
 
void main()
{
    int hot_dogs = 10;
    int burgers = 20;
 
    auto total = hot_dogs + burgers;
 
    string text = burgers + " burgers";  // Error! Incompatible types int and string
 
    writeln(hot_dogs, " hot dogs and ", burgers, " burgers");
    writeln(total, " total items");
}

Concepts[edit]

In this lesson we see the declaration and assignment of variables.

Declaration Syntax[edit]

The syntax of declaring variables is
type identifier;
You can also assign a value at the same time.
type identifier = value;

Declaring Multiple Variables in the Same Line[edit]

D allows you to declare multiple variables of the same type in the same line. If you write:

int i, j, k = 30;

i, j, and k are all declared as ints but only k is assigned 30. It is the same as:

int i, j;
int k = 30;

Implicit Type Inference[edit]

If the declaration starts with auto, then the compiler will automatically infer the type of the declared variable. In fact, it doesn't have to be auto. Any storage class would work. Storage classes are built-in D constructs such as auto or immutable. This code declares an unchangeable variable a with a value of 3. The compiler figures out that the type is int.

immutable a = 3;

You will learn much more about storage classes later.

More about writeln[edit]

writeln is a very useful function for writing to stdout. One thing is special about writeln: it can take variables of any type. It can also take an unlimited amount of arguments. For example:

writeln("I ate ", 5, " hot dogs and ", 2, " burgers.");
// prints I ate 5 hot dogs and 2 burgers.

Don't worry, there is nothing magical about writeln. All the functions in the write family are implemented (in 100% valid D code) in stdio.d, which is in the Phobos standard library.

Tips[edit]

  • Syntax like this: int i, j, k = 1, 2, 3; is not allowed.
  • Syntax like this: int, string i, k; is also not allowed.
  • auto is not a type. You cannot do this: auto i; because there's no way the compiler can infer the type of i. auto is merely a storage class, which tells the compiler to infer the type from the value that you assign it to in that same line.