Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Learning D - Your First Program

Ok, now that we know how to get D working and how files look lets have an example. In this example we will read in the user's name and print out a message using it.

#!/usr/bin/dmd -run

/* Imports */
import std.stdio;
import std.string : chop;

/* Code */
int main(char[][] args)
{
    writef("What is your name? ");
    char[] name = chop(readln());
    writefln("Hello %s! Say hello to your first program. Well, thats all I say so, goodbye ",name,name);
    getc(stdin);
    return 0;
}

Whew... Thats a lot of things to take into account. Lets break this up into sections.

Section 1 - Script Line

#!/usr/bin/dmd -run

As stated earlier, this line tells Posix (Unix and Linux) users how to run this script. Thats all it does. It must be the very first line of the file.

Section 2 - Imports

/* Imports */
import std.stdio;
import std.string : chop;

This brings in two things that are very commonly used std.stdio and std.string we can go into those more in depth later. For now, know that these two modules are used for manipulating text the user inputs and sees in a console/terminal. The first word on each line is import. This is a reserved word in D used to bring in modules of code, after it is used write down which module(s) to import. Why are there semicolons ( ; ) after the modules? That is because in D code is separated into sections called statements. At the end of every statement there is a semicolon.

Section 3 - Code

/* Code */
int main(char[][] args)
{
    writef("What is your name? ");
    char[] name = chop(readln());
    writefln("Hello %s! Say hello to your first program. Well, thats all I say so, goodbye ",name,name);
    getc(stdin);
    return 0;
}

This is what your program truly is. The important thing to note is that int main(char[][]) is what the compiler sees as the start of a program. All of the other code you see is inside of the function main but we can learn more about this after we know what kind of operations and data D has to offer. For now, see how the program compiles being sure that you can execute the results. Your output should look something like this if you are using the console:

C:\D\dmd\bin\..\..\dm\bin\link.exe firstprogram,,,c:\d\dmd\lib\ws2_32.lib+user32+kernel32/noi;
What is your name? Bradley
Hello Bradley! Say hello to your first program. Well, thats all I say. Goodbye Bradley

If this does not look anything like this and you get a compile error, make sure the the code is the exact same as the code above and you are using the latest D compiler.

If you really want to go into what is going on go to the line by line explanation.

Next: Data Structures in D