D (programming language)

D (programming language)
D programming language
Paradigm(s) multi-paradigm: imperative, object-oriented, functional, meta
Appeared in 1999 (1999)
Designed by Walter Bright
Stable release 1.071 / 2.056 (October 27, 2011; 26 days ago (2011-10-27)[1][2])
Typing discipline strong, static
Major implementations DMD (reference implementation), GDC, LDC
Influenced by C, C++, C#, Java, Eiffel, Python, Ruby
Influenced MiniD, DScript, Vala
OS DMD: Unix-like, Windows, Mac OS X
License GPL (DMD frontend), Boost (standard and runtime libraries), Source-available (DMD backend), Fully open-source (LDC and GDC)[3]
Usual filename extensions .d
Website www.d-programming-language.org
Wikibooks logo D Programming at Wikibooks

The D programming language is an object-oriented, imperative, multi-paradigm, system programming language designed by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++. D has redesigned some C++ features and has been influenced by concepts used in other programming languages, such as Java, Python, Ruby, C#, and Eiffel.



D is designed with lessons learned from practical C++ usage rather than from a theoretical perspective. Even though it uses many C/C++ concepts it also discards some, and as such is not compatible with C/C++ source code. It adds to the functionality of C++ by also implementing design by contract, unit testing, true modules, garbage collection, first class arrays, associative arrays, dynamic arrays, array slicing, nested functions, inner classes, closures, anonymous functions, compile time function execution, lazy evaluation and has a reengineered template syntax. D retains C++'s ability to do low-level coding, and adds to it with support for an integrated inline assembler. C++ multiple inheritance is replaced by Java style single inheritance with interfaces and mixins. D's declaration, statement and expression syntax closely matches that of C++.

The inline assembler typifies the differences between D and application languages like Java and C#. An inline assembler lets programmers enter machine-specific assembly code within standard D code, a method often used by system programmers to access the low-level features of the processor needed to run programs that interface directly with the underlying hardware, such as operating systems and device drivers.

D has built-in support for documentation comments, allowing automatic documentation generation.

Programming paradigms

D supports three main programming paradigmsimperative, object-oriented, and metaprogramming.

D 2.0 adds two programming paradigms - functional, concurrent (Actor model).


Imperative programming in D is almost identical to C. Functions, data, statements, declarations and expressions work just as in C, and the C runtime library can be accessed directly. Some notable differences between D and C in the area of imperative programming include D's foreach loop construct, which allows looping over a collection, and nested functions, which are functions that are declared inside of another and may access the enclosing function's local variables.


Object-oriented programming in D is based on a single inheritance hierarchy, with all classes derived from class Object. D does not support multiple inheritance; instead, it uses Java-style interfaces, which are comparable to C++ pure abstract classes, and mixins, which allow separating common functionality out of the inheritance hierarchy. Additionally, D 2.0 allows declaring static and final (non-virtual) methods in interfaces.


Metaprogramming is supported by a combination of templates, compile time function execution, tuples, and string mixins. The following examples demonstrate some of D's compile-time features.

Templates in D can be written in a more function-like style than those in C++. This is a regular function that calculates the factorial of a number:

ulong factorial(ulong n)
    if(n < 2)
        return 1;
        return n * factorial(n - 1);

Here, the use of static if, D's compile-time conditional construct, is demonstrated to construct a template that performs the same calculation using code that is similar to that of the above function:

template Factorial(ulong n)
    static if(n < 2)
        const Factorial = 1;
        const Factorial = n * Factorial!(n - 1);

In the following two examples, the template and function defined above are used to compute factorials. The types of constants need not be specified explicitly as the compiler infers their types from the right-hand sides of assignments:

const fact_7 = Factorial!(7);

This is an example of compile time function execution. Ordinary functions may be used in constant, compile-time expressions provided they meet certain criteria:

const fact_9 = factorial(9);

The std.metastrings.Format template performs printf-like data formatting, and the "msg" pragma displays the result at compile time:

import std.metastrings;
pragma(msg, Format!("7! = %s", fact_7));
pragma(msg, Format!("9! = %s", fact_9));

String mixins, combined with compile-time function execution, allow generating D code using string operations at compile time. This can be used to parse domain-specific languages to D code, which will be compiled as part of the program:

import FooToD; // hypothetical module which contains a function that parses Foo source code 
               // and returns equivalent D code
void main()


D 2.0 only.

import std.algorithm, std.range, std.stdio;
int main()
    int[] a1 = [0,1,2,3,4,5,6,7,8,9];
    int[] a2 = [6,7,8,9];
    immutable pivot = 5; // must be immutable to allow access from inside mysum
    int mysum(int a, int b) pure // pure function
        if (b <= pivot) // ref to enclosing-scope
            return a + b;
            return a;
    auto result = reduce!(mysum)( chain(a1, a2) ); // passing a delegate (closure)
    writeln("Result: ", result); // output is "15"
    return 0;


D 2.0 only.

import std.concurrency, std.stdio, std.typecons;
int main()
    auto tid = spawn(&foo); // spawn a new thread running foo()
    foreach(i; 0 .. 10)
        tid.send(i);   // send some integers
    tid.send(1.0f);    // send a float
    tid.send("hello"); // send a string
    tid.send(thisTid); // send a struct (Tid)
    receive( (int x) { writeln("Main thread received message: ", x); } );
    return 0;
void foo()
    bool cont = true;
    while (cont)
        receive( // delegates are used to match the message type
            (int msg) { writeln("int received: ", msg); },
            (Tid sender) { cont = false; sender.send(-1); },
            (Variant v) { writeln("huh?"); } // Variant matches any type

Memory management

Memory is usually managed with garbage collection, but specific objects can be finalized immediately when they go out of scope. Explicit memory management is possible using the overloaded operators new and delete, and by simply calling C's malloc and free directly. Garbage collection can be controlled: programmers can add and exclude memory ranges from being observed by the collector, can disable and enable the collector and force a generational or a full collection cycle.[4] The manual gives many examples of how to implement different highly optimized memory management schemes for when garbage collection is inadequate in a program.


D knows static arrays with boundaries known at compile time and dynamic arrays, which can grow and shrink at runtime.

void foo()
    int[4] static_int_array = new int[4]; // create array of four int's with indeces 0 to 3
    int[] dynamic_int_array = new int[4]; // some as above, but array is dynamic
    auto some_other_array = static_int_array; // another static int array is created, values are copied
    auto yet_another_array = static_int_array[]; // yet_another_array would be dynamic, but points to the same memory location as static_int_array
    dynamic_int_array.length -= 1; // shrink dynamic_int_array, so it would have three items now
    yet_another_array.length += 4; // grow yet_another_array, so it would have eight items now

Arrays can be sliced, like in Python (programming language), and concatenated. D supports array-wise operations.

void foo()
    int[] bar = [1, 2, 3, 4, 5];
    int[] baz = bar[1 .. $ - 1]; // baz would contain 2, 3, 4 now
    baz ~= [99, 98]; // baz would contain 2, 3, 4, 99, 98
    baz[] *= 2; // multiply all elements with 2, so that baz contains 4, 6, 8, 198, 196

Like C#, D supports jagged arrays. Static and dynamic behaviour can be mixed at the same time.

void foo()
    auto jagged_array = new int[][4]; // created a dynamic array whose items are static arrays of four int's

Arrays can be associative, like maps, hashtables, or dictionaries in other lanugages. If they are defined in code, JSON-like syntax can be used.

import std.stdio;
import std.conv;
void foo()
    int[string] birthyears = [ "Tobias" : 2008, "Oliver" : 2008, "Amelie" : 2008, "Jana" : 2010 ];
    foreach (who, when; birthyears)
        writeln(to!string(who) ~ " was born in " ~ to!string(when));

Interaction with other systems

C's application binary interface (ABI) is supported as well as all of C's fundamental and derived types, enabling direct access to existing C code and libraries. C's standard library is part of standard D.

C++'s ABI is not fully supported, although D can access C++ code that is written to the C ABI. The D parser understands an extern (C++) calling convention for limited linking to C++ objects, but it is only implemented in D 2.0.

On Microsoft Windows, D can access Component Object Model (COM) code.


GtkD is a language binding of the GTK+ graphical widget toolkit for the D programming language. As of 2011, the latest version is 1.5.1 which wraps GTK+ 2.22.[5] It is compatible with both D 1.0 and D 2.0, either with the Phobos or the Tango system library.[6]


Hello world in D with GtkD:

import gtk.MainWindow;
import gtk.Label;
import gtk.Main;
void main(string[] args)
    MainWindow win = new MainWindow("Hello world!");
    win.setDefaultSize(250, 150);
    win.add(new Label("Hello world!"));

See also: Code examples


The D programming language exists in two versions: 1.0 and 2.0. D 1.0 became stable with the release of D 2.0, on June 17, 2007, and further additions to the language have since been added to 2.0. The release of Andrei Alexandrescu's book The D Programming Language on June 12, 2010 marked the stabilization of D 2.0.

D 1.0

Version 1.00 of the Digital Mars D compiler was released on Jan 2, 2007.[7] Since the release of D 2.0, D 1.0 and its DigitalMars implementation only received bugfixes and insignificant features which did not affect backwards compatibility.

D 2.0

D 2.0 introduced multiple new features, some of which broke compatibility with D 1.0 code.[8] Some of these features are:[9]

  • Support for enforcing const-correctness:
    • D differentiates between mutable references to immutable data, const references to mutable data, and combinations thereof
    • const and immutable keywords are transitive.
  • Limited support for linking with code written in C++.
  • Iteration with foreach over defined range only.
  • Support for "real" closures. Previously closures couldn't be safely returned from functions, because stack-allocated variables would become inaccessible.
  • Support for pure functions which can only access immutable data and call other pure functions. This ensures a pure function has no side effects (the same stack inputs always result in the same outputs and outputs exist only through return values). Together with real closure support this allows Functional Programming in D and also opens theoretical paths for safe automatic threading.
  • nothrow functions.
  • "safe" subset (SafeD), which can't directly access memory not belonging to process (only limited set of casts and pointer arithmetic is possible in such code).
  • Vector operations, i.e. a[] = b[] + c[] (element-wise summation of two dynamic/static arrays), or a[] *= 3 (multiply by 3 each element of array).
  • Classic global storage defaults to Thread Local Storage.
  • Changes to standard Phobos library, including metaprogramming and functional programming additions.
  • Template function literals


Most current D implementations compile directly into machine code for efficient execution.

  • DMD — The Digital Mars D compiler is the official D compiler by Walter Bright. The compiler front-end is licensed under both the Artistic License and the GNU GPL; the source code for the front-end is distributed with the compiler binaries. The compiler back-end source code is available but not under an open source license. It implements 1.0 and 2.0 versions.
  • GDC — A front-end for the GCC back-end, built using the open DMD compiler source code. Development snapshots also support D version 2.0.[10]
  • LDC — A compiler based on the DMD front-end that uses Low Level Virtual Machine (LLVM) as its compiler back-end. The first release-quality version was published on January 9, 2009.[11] It supports version 2.0.[12]
  • D Compiler for .NET — A back-end for the D programming language 2.0 compiler.[13][14] It compiles the code to Common Intermediate Language (CIL) bytecode rather than to machine code. The CIL can then be run via a Common Language Infrastructure (CLR) virtual machine.

Development tools

Editors and integrated development environments (IDEs) supporting D include Eclipse, Microsoft Visual Studio, SlickEdit, Emacs, vim, SciTE, Smultron, TextMate, Zeus,[15] and Geany among others.[16]

  • Eclipse plug-ins for D include: DDT,[17] and Descent (dead project).[18]
  • Visual Studio integration is provided by VisualD.[19]
  • Vim supports both syntax highlighting and code completion (through patched Ctags).
  • A bundle is available for TextMate, and the Code::Blocks IDE includes partial support for the language. However, standard IDE features such as code completion or refactoring are not yet available, though they do work partially in Code::Blocks (due to D's similarity to C).
  • A plugin for Xcode is available, D for Xcode, to enable D-based projects and development.[20]

Open source D IDEs for Windows exist, some written in D, such as Poseidon,[21] D-IDE,[22] and Entice Designer.[23]

D applications can be debugged using any C/C++ debugger, like GDB or WinDbg, although support for various D-specific language features is extremely limited. On Windows, D programs can be debugged using Ddbg, or Microsoft debugging tools (WinDBG and Visual Studio), after having converted the debug information using cv2pdb. The commercial ZeroBUGS debugger for Linux has experimental support for the D language. Ddbg can be used with various IDEs or from the command line; ZeroBUGS has its own graphical user interface (GUI).

Problems and controversies

Division concerning the standard library

While D 2.0 no longer has a library split, in D 1.0, the standard library was called Phobos. Some members of the D community had thought that Phobos was too simplistic and that it had numerous quirks and other issues, and a replacement of the library called Tango was written.[24] However, in the D 1.0 branch, Tango and Phobos are incompatible due to different runtime support APIs (the garbage collector, threading support, etc.). The existence of two libraries, both widely in use at the time, led to significant problems where some packages use Phobos and others use Tango.

This problem has been addressed in D 2.0 by merging the core runtime, called druntime, and improving the problems in Phobos that led to the original fork.

Unfinished support for shared/dynamic libraries

Unix's Executable and Linkable Format (ELF) shared libraries are supported to an extent using the GDC compiler.

On Windows systems, dynamic-link library (DLLs) are supported and allow D's garbage collector-allocated objects to be safely passed to C functions, since the garbage collector scans the stack for pointers. However, there currently are limitations with using multiple modules written in D within the same application, due to issues such as possible incompatible garbage collector instances, data structure (e.g. associative array) implementations, and differing run-time type information.[25]

String handling

The language has three distinct character types (char, wchar and dchar) and three string aliases (string, wstring and dstring, which are simply dynamic arrays of the former) which represent UTF-8, UTF-16 and UTF-32 code units and strings respectively. For performance reasons, string slicing and the length property operate on code units rather than code points (characters), which frequently confuses developers.[26] Since UTF-8 and UTF-16 are variable-length character encodings, access by code point index in constant time is not possible without maintaining additional lookup tables. Code that needs fast random access to code points should convert strings to UTF-32 first, or use lookup tables. However, this is also true for other programming languages supporting Unicode, like Java and C# that use UTF-16, and thus may need surrogate pairs to represent some code points.


Example 1

This example program prints its command line arguments. The main function is the entry point of a D program, and args is an array of strings representing the command line arguments. A string in D is an array of characters, represented by char[] in D 1.0, or immutable(char)[] in D 2.0 alpha. Newer versions of the language define string as an alias for char[] or immutable(char)[], however, an explicit alias definition is necessary for compatibility with older versions.

import std.stdio: writefln;
void main(string[] args)
    foreach (i, arg; args)
        writefln("args[%d] = '%s'", i, arg);

The foreach statement can iterate over any collection, in this case it is producing a sequence of indexes (i) and values (arg) from the array args. The index i and the value arg have their types inferred from the type of the array args.

Using the Tango library, the above code would be as follows:

import tango.io.Stdout;
void main(char[][] args)
    foreach (i, arg; args)
        Stdout("args[")(i)("] = '")(arg)("'").newline();

Example 2

The following shows several capabilities of D in a very short program. It iterates the lines of a text file named words.txt that contains a different word on each line, and prints all the words that are anagrams of other words.

import std.stdio: writefln;
import std.stream: BufferedFile;
import std.string: tolower, join;
void main()
    string[][string] signature2words;
    foreach (string line; new BufferedFile("words.txt"))
        signature2words[line.tolower.sort] ~= line.dup;
    foreach (words; signature2words)
        if (words.length > 1)
            writefln(words.join(" "));
  1. The type of signature2words is a built-in associative array that maps string keys to arrays of strings. It is similar to defaultdict(list) in Python.
  2. BufferedFile yields lines lazily, without their newline, for performance the line it yields is just a view on a string, so it has to be copied with dup to have an actual string copy that can be used later (the dup property of arrays returns a duplicate of the array).
  3. The ~= operator appends a new string to the values of the associate array.
  4. tolower and join are string functions that D allows to use with a method syntax, their names are often similar to Python string methods. The tolower converts an ASCII string to lower case and join(" ") joins an array of strings into a single string using a single space as separator.
  5. The sort property sorts the array in place, creating a unique signature for words that are anagrams of each other.
  6. The second foreach iterates on the values of the associative array, it's able to infer the type of words.

See also


  1. ^ "Changelog". D Programming Language 1.0. Digital Mars. http://www.digitalmars.com/d/1.0/changelog.html. Retrieved 27 October 2011. 
  2. ^ "Changelog". D Programming Language 2.0. Digital Mars. http://www.digitalmars.com/d/2.0/changelog.html. Retrieved 27 October 2011. 
  3. ^ FAQ of digitalmars
  4. ^ "std.gc". D Programming Language 1.0. Digital Mars. http://www.digitalmars.com/d/1.0/phobos/std_gc.html. Retrieved 6 July 2010. 
  5. ^ Official homepage
  6. ^ http://www.dsource.org/projects/gtkd
  7. ^ "D Change Log (older versions)". D Programming Language 1.0. Digital Mars. http://www.digitalmars.com/d/1.0/changelog2.html. Retrieved 6 July 2010. 
  8. ^ "Migrating D1 Code to D2". D Programming Language 2.0. Digital Mars. http://www.digitalmars.com/d/2.0/D1toD2.html. Retrieved 6 July 2010. 
  9. ^ "D 2.0 Enhancements from D 1.0". D Programming Language 2.0. Digital Mars. http://www.digitalmars.com/d/2.0/features2.html. Retrieved 6 July 2010. 
  10. ^ "gdc project on bitbucket". http://bitbucket.org/goshawk/gdc/. Retrieved 3 July 2010. 
  11. ^ "LLVM D compiler project on DSource". http://dsource.org/projects/ldc. Retrieved 3 July 2010. 
  12. ^ [1]
  13. ^ "D .NET project on CodePlex". http://dnet.codeplex.com/. Retrieved 3 July 2010. 
  14. ^ Jonathan Allen (15 May 2009). "Source for the D.NET Compiler is Now Available". InfoQ. http://www.infoq.com/news/2009/05/D-Source. Retrieved 6 July 2010. 
  15. ^ Zeus
  16. ^ "Wiki4D - Editor Support". http://www.prowiki.org/wiki4d/wiki.cgi?EditorSupport. Retrieved 3 July 2010. 
  17. ^ DDT
  18. ^ Descent
  19. ^ VisualD
  20. ^ D for Xcode
  21. ^ Poseidon
  22. ^ D-IDE
  23. ^ Entice Designer
  24. ^ "Wiki4D - Standard Lib". http://www.prowiki.org/wiki4d/wiki.cgi?StandardLib. Retrieved 6 July 2010. 
  25. ^ "Wiki4D - BestPractices/DLL". http://www.prowiki.org/wiki4d/wiki.cgi?BestPractices/DLL. Retrieved 6 July 2010. 
  26. ^ Keep, Daniel. "Wiki4D - Text in D". http://www.prowiki.org/wiki4d/wiki.cgi?DanielKeep/TextInD. Retrieved 6 July 2010. 

Further reading

External links

Wikimedia Foundation. 2010.

Look at other dictionaries:

  • Programming language — lists Alphabetical Categorical Chronological Generational A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that… …   Wikipedia

  • Programming language theory — (commonly known as PLT) is a branch of computer science that deals with the design, implementation, analysis, characterization, and classification of programming languages and programming language features. It is a multi disciplinary field, both… …   Wikipedia

  • Programming Language Design and Implementation — (PLDI) is one of the ACM SIGPLAN s most important conferences. The precursor of PLDI was the Symposium on Compiler Optimization, held July 27–28, 1970 at the University of Illinois at Urbana Champaign and chaired by Robert S. Northcote. That… …   Wikipedia

  • Programming Language for Business — or PL/B is a business oriented programming language originally called DATABUS and designed by Datapoint in the early 1970s as an alternative to COBOL because its 8 bit computers could not fit COBOL into their limited memory, and because COBOL did …   Wikipedia

  • programming language — ➔ language * * * programming language UK US noun [C] ► COMPUTER LANGUAGE(Cf. ↑computer language) …   Financial and business terms

  • programming language — Language Lan guage, n. [OE. langage, F. langage, fr. L. lingua the tongue, hence speech, language; akin to E. tongue. See {Tongue}, cf. {Lingual}.] [1913 Webster] 1. Any means of conveying or communicating ideas; specifically, human speech; the… …   The Collaborative International Dictionary of English

  • Programming Language One — Programming Language One, oft als PL/I (auch PL/1, PL1 oder PLI) abgekürzt ist eine Programmiersprache, die in den 1960er Jahren von IBM entwickelt wurde. Die Bezeichnung PL/1 ist vor allem in Deutschland gebräuchlich. Ursprünglich wurde PL/I… …   Deutsch Wikipedia

  • Programming Language 1 — noun A computer programming language which combines the best qualities of commercial and scientific oriented languages (abbrev PL/1) • • • Main Entry: ↑programme …   Useful english dictionary

  • Programming Language —   [engl.], Programmiersprache …   Universal-Lexikon

  • Programming language specification — A programming language specification is an artifact that defines a programming language so that users and implementors can agree on what programs in that language mean.A programming language specification can take several forms, including the… …   Wikipedia

  • programming language — noun (computer science) a language designed for programming computers • Syn: ↑programing language • Topics: ↑computer science, ↑computing • Hypernyms: ↑artificial language …   Useful english dictionary