Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

Program Structure, Imports and Printing in D

Understand how a D program is organized: modules, selective imports, comments, statements, the print family writeln and writefln, and reading input with readln.

Every D program is a set of modules, and every module is a list of declarations: functions, types, variables and imports. This lesson maps that structure, then teaches the tools you will use in every example: comments, selective imports, formatted output and reading a line of input. All D listings are read-only; two C stand-ins let you practice the formatting and input ideas.

Anatomy of a module

D
/// Computes a rectangle's area. (A documentation comment.)
module shapes;

import std.stdio;               // everything from std.stdio
import std.math : sqrt, PI;     // only these two names

enum double unit = 1.0;         // a compile-time constant

double area(double w, double h) // a function
{
    return w * h;
}

void main()
{
    writeln("Area: ", area(3, 4));
    writeln("Diagonal: ", sqrt(3.0 * 3 + 4.0 * 4));
}

Reading top to bottom:

  1. A module line is optional for a single file; without it the name is taken from the file.
  2. import statements bring in other modules. import std.math : sqrt, PI; is a selective import: only the listed names enter scope, which keeps your namespace tidy and documents what you use.
  3. Declarations may appear in any order. Unlike C, D does not require a function to be declared before use at module level.
  4. main is the entry point.

Running this prints Area: 12 and Diagonal: 5.

Comments

D has three comment forms:

D
// line comment
/* block comment */
/+ nesting block comment /+ can contain another +/ and still work +/

The nesting form /+ ... +/ is useful for commenting out code that already contains comments. Comments that start with /// or /** */ are documentation comments, processed by the compiler's documentation generator (dmd -D).

Imports in other places

You can import inside a function, which limits the names to that scope and avoids loading unused modules:

D
void report(double x)
{
    import std.stdio : writefln;
    writefln("Value: %.2f", x);
}

You can also rename on import (import std.stdio : out = writeln;), or import a module only for its qualified names with static import std.math; and then write std.math.sqrt(2.0).

The print family

All live in std.stdio:

Function Behavior
write(a, b) Prints values with no separator, no newline
writeln(a, b) Same, plus a newline
writef(fmt, ...) Formatted, no newline
writefln(fmt, ...) Formatted, plus a newline

Format strings use printf-like specifiers, and %s works for any type because D can print it generically:

D
import std.stdio;

void main()
{
    int n = 42;
    double pi = 3.14159265;
    string name = "D";
    writefln("%s has %d letters", name, name.length);   // D has 1 letters
    writefln("n=%5d|%-5d|%05d", n, n, n);               // n=   42|42   |00042
    writefln("pi=%.3f %e", pi, pi);                      // pi=3.142 3.141593e+00
    int[] list = [3, 1, 2];
    writeln(list);                                       // [3, 1, 2]
}

Unlike C, a mismatched specifier is caught: writefln checks the format at run time and throws a FormatException if a type does not fit (for example %d with a string). Passing the format as a template argument, writefln!"%d"(5), makes the compiler check it.

Reading input

D
import std.stdio;
import std.string : strip;
import std.conv : to;

void main()
{
    write("Your age? ");
    string line = readln();           // includes the trailing newline
    int age = line.strip.to!int;      // strip whitespace, then convert
    writeln("Next year: ", age + 1);
}

readln returns the whole line including \n (or an empty string at end of input), so you usually strip it. std.conv.to!int converts and throws a ConvException if the text is not a number. readf(" %d", &n) is the formatted alternative, and note the leading space that skips whitespace.

Statements, blocks and scope

A statement ends with ;. Curly braces make a block with its own scope: a variable declared inside is invisible outside. D does not allow a variable to shadow a local of an enclosing function scope in the same function, which prevents a whole class of mistakes that C allows silently.

C stand-ins for formatting and input

C C stand-in: format specifiers (like writefln)

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 output is D has 1 letters, then n= 42|42 |00042, then pi=3.142 3.141593e+00. These are the same specifiers writefln accepts, so you can predict D's output from C knowledge.

C C stand-in: read a line and convert it

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.

With the preset input 41 it prints Next year: 42. Try changing the input box to abc to see the error path that D would report as an exception.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does import std.math : sqrt, PI; do?

    A selective import limits the names brought into scope.
  2. 2. Which comment form can be nested?

    Only /+ +/ comments nest.
  3. 3. What does readln() return?

    The newline is kept, so you usually call strip.
  4. 4. Which function prints formatted text followed by a newline?

    writefln formats and adds the newline; writef does not.

Summary

  • A module holds declarations in any order; main starts the program.
  • Use selective imports, and import inside functions to limit scope.
  • writeln, writefln and friends print any type; readln reads a line.
  • /+ +/ comments nest; /// comments document.

Next: Variables, types and initialization