| Topics: | Language and Phobos -DGui (example placeholder - can be any library) | |
| Lessons: | 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -T | Next |
| Subpages: | String Formatting -Advanced Info about std.stdio's Write Functions |
In this lesson, you will learn how to use the Phobos library to write to the console.Also, you will learn some about the structure of D programs.
We will start with the absolutely necessary Hello World example.
/* This program prints a hello world message to the console. */importstd.stdio;voidmain(){writeln("Hello, World!");}
In this lesson we see theimport statement, themain function, the Phobos standard library in use, and also acode comment.
The Phobos library contains thestd.stdio module which in turn contains thewriteln function (along with various other functions).In order to use that function, you must first import that module.Notice that statements in D end in a semicolon.
All executable D programs contain a main function.This function does not return a value, so it is declared "void" (Technically, this is an over-simplification. Return values ofmain will be explained in more detail later.)This function is executed when the program runs.
Function body code is enclosed in curly brackets.Although the indentation and whitespace is only for the reader, not for the compiler, make sure you indent and format your code properly and consistently; it's generally a good coding practice.
writeln is for writing to the standard output (console in this case). You can supply a string such as"Hello, World!" as an argument, and that string will be printed out. There are four basic flavors of this function: With or without formatting, and with or without a trailing newline. To demonstrate how they work, all of the following are equivalent (although the first and thirds ones don't flushstdout on Windows):
// write: Plain vanillawrite("Hello, World!\n");// The \n is a newlinewrite("Hello, ","World!","\n");write("Hello, ");write("World!");write("\n");
// writeln: With automatic newlinewriteln("Hello, World!");writeln("Hello, ","World!");
// writef: Formatted outputwritef("Hello, %s!\n","World");
// writefln: Formatted output with automatic newlinewritefln("Hello, %s!","World");writefln("%s, %s!","Hello","World");writefln("%2$s, %1$s!","World","Hello");// Backwards order
The first few lines of this program are comments. They are ignored by the compiler. Block comments are enclosed in/* */. Line comments continue after//.
This is an example of a line comment:
importstd.stdio;// I am a commentvoidmain(){}//this program does nothing
D also supports nested block comments, enclosed in/+ +/:
/+thisIsCommentedOut(); /+ thisIsCommentedOut(); +/thisIsSTILLCommentedOut();+/
This is different from ordinary block comments which behave just like in C:
/*thisIsCommentedOut(); /* thisIsCommentedOut(); */thisIsNOTCommentedOut();// The following line is a syntax error:*/
writeln is different fromwrite because it adds a newline to the end.