Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning D
Learning D

Learning D: Leverage the modern convenience and modelling power of the D programming language to develop software with native efficiency

eBook
$9.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learning D

Chapter 2. Building a Foundation with D Fundamentals

In this chapter and the next, we're going to look at the fundamental building blocks of D programming. There's a lot of information to cover, so our focus in both chapters will primarily be on the syntax, differences from other C-family languages, and how to avoid common beginner mistakes.

If you enter the code snippets into a text editor and try to compile them as you work through this chapter and the rest of the book, please keep the following in mind. Many of the snippets make use of one or more functions from std.stdio. In order to be successfully compiled, they all require a main function. However, both declarations are often missing from the snippets listed in the book in the interest of saving space. Use the following as a template to implement any such snippets yourself:

import std.stdio;
void main() {
    // Insert snippet here
}

Here's how this chapter is going to play out:

  • The very basics: Identifiers,...

The very basics

With the exception of source code comments, everything in this section is required knowledge for anyone who intends to successfully compile a D program.

Identifiers

The names of variables, functions, user-defined types, and so on, are all identifiers. Identifiers are case-sensitive and can consist of any combination and number of Universal Character Names (UCN), underscores, and digits. D does not itself define what constitutes a valid UCN. Instead, it refers to the list of valid UCNs specified in Annex D of the C99 standard. Aside from the English alphabet, characters from several languages are valid UCNs. Henceforth, I will refer to UCNs as letters. Identifiers in this book will be constrained to the English alphabet.

There are a few rules to follow when choosing identifiers:

  • The first character in an identifier can only be a letter or an underscore.
  • The use of two leading underscores is reserved for the compiler implementation. This is currently not enforced by the compiler...

Basic types

Most of D's basic data types will be familiar to C-family programmers. In this section, we're first going to look at what the basic data types are. Then we'll discuss a couple of features that are related not only to the basic types, but to all types.

The types

First up, D includes the special type void to mean no type. There is no such thing as a variable of type void. As in C, void is used to indicate that a function does not return a value. void pointers can be declared to represent pointers to any type.

Instances of the bool type are guaranteed to be eight bits in size and can hold one of two possible values: true and false. In any expression that expects a Boolean value, any zero value is converted to false and non-zero is converted to true. Conversely, in any expression that expects a numeric type, false and true are converted to 0 and 1. Variables of type bool are initialized to false by default.

D supports signed and unsigned versions of integral types in...

Basic operators

This section is a whirlwind tour of the basic operators D supports. For the most part, things are the same as they are in C. There are a few minor differences that will be highlighted as we come to them. More operators will appear later in this chapter and throughout the book. You can read more about D's operators at http://dlang.org/expression.html.

Arithmetic operators

All of the common arithmetic operators are available: +, -, *, / and %, representing addition, subtraction, multiplication, division, and modulus respectively. Additionally, D has an exponentiation operator, ^^, which raises the left operand to an exponent (power) represented by the right operand. For example, 22 can be expressed as 2 ^^ 2.

D also supports the standard increment and decrement operators. In the prefix form (++x and --x), the result of the expression is the new value. In the postfix form (x++ and x--), the result is the original value of the operand. To be more explicit, under the hood...

Derived data types

In this section, we're going to observe D's take on pointers, arrays, strings, and associative arrays. Much of what we'll cover here is very different from other C-family languages.

Pointers

As in other languages that support them, pointers in D are special variables intended to hold memory addresses. Take a moment to compile and run the following:

int* p;
writeln("p's value is ", p);
writeln("p's type is ", typeid(p));
writeln("p's size is ", p.sizeof);	

First, look at the declaration. It should look very familiar to many C-family programmers. All pointer declarations are default initialized to null, so here the first call to writeln prints "null" as the value. The type of p printed in the second writeln is int*. The last line will print 4 in 32-bit and 8 in 64-bit.

So far so good. Now look at the following line and guess what type b is:

int* a, b;

No, b is not an int, it is an int*. The equivalent C or C...

Control flow statements

D includes the traditional loop and conditional statements found in other C-family languages. It also supports the infamous goto statement. It has a couple of other useful statements, such as a built-in foreach statement and a rather unique scope statement. In this section, we're going to look at examples of each of the first two. Because of their relation with exceptions, scope statements are included in detail in the next chapter.

Traditional loops

In terms of looping constructs, we have for, do, and do-while. The syntax and behavior should be familiar. Here is an example of each iterating over an array:

auto items = [10,20,30,40,50];
for(int i=0; i<items.length; ++i)
  writeln(items[i]);

int i = 0;
while(i < items.length)
  writeln(items[i++]);

i = 0;
do {
  writeln(items[i++]);
} while(i < items.length);

No surprises there. The braces are optional with for and while when they only contain one statement. When a loop with an empty body is desired, the...

The very basics


With the exception of source code comments, everything in this section is required knowledge for anyone who intends to successfully compile a D program.

Identifiers

The names of variables, functions, user-defined types, and so on, are all identifiers. Identifiers are case-sensitive and can consist of any combination and number of Universal Character Names (UCN), underscores, and digits. D does not itself define what constitutes a valid UCN. Instead, it refers to the list of valid UCNs specified in Annex D of the C99 standard. Aside from the English alphabet, characters from several languages are valid UCNs. Henceforth, I will refer to UCNs as letters. Identifiers in this book will be constrained to the English alphabet.

There are a few rules to follow when choosing identifiers:

  • The first character in an identifier can only be a letter or an underscore.

  • The use of two leading underscores is reserved for the compiler implementation. This is currently not enforced by the compiler...

Basic types


Most of D's basic data types will be familiar to C-family programmers. In this section, we're first going to look at what the basic data types are. Then we'll discuss a couple of features that are related not only to the basic types, but to all types.

The types

First up, D includes the special type void to mean no type. There is no such thing as a variable of type void. As in C, void is used to indicate that a function does not return a value. void pointers can be declared to represent pointers to any type.

Instances of the bool type are guaranteed to be eight bits in size and can hold one of two possible values: true and false. In any expression that expects a Boolean value, any zero value is converted to false and non-zero is converted to true. Conversely, in any expression that expects a numeric type, false and true are converted to 0 and 1. Variables of type bool are initialized to false by default.

D supports signed and unsigned versions of integral types in 8-, 16-, 32-, and...

Basic operators


This section is a whirlwind tour of the basic operators D supports. For the most part, things are the same as they are in C. There are a few minor differences that will be highlighted as we come to them. More operators will appear later in this chapter and throughout the book. You can read more about D's operators at http://dlang.org/expression.html.

Arithmetic operators

All of the common arithmetic operators are available: +, -, *, / and %, representing addition, subtraction, multiplication, division, and modulus respectively. Additionally, D has an exponentiation operator, ^^, which raises the left operand to an exponent (power) represented by the right operand. For example, 22 can be expressed as 2 ^^ 2.

D also supports the standard increment and decrement operators. In the prefix form (++x and --x), the result of the expression is the new value. In the postfix form (x++ and x--), the result is the original value of the operand. To be more explicit, under the hood D is...

Derived data types


In this section, we're going to observe D's take on pointers, arrays, strings, and associative arrays. Much of what we'll cover here is very different from other C-family languages.

Pointers

As in other languages that support them, pointers in D are special variables intended to hold memory addresses. Take a moment to compile and run the following:

int* p;
writeln("p's value is ", p);
writeln("p's type is ", typeid(p));
writeln("p's size is ", p.sizeof);	

First, look at the declaration. It should look very familiar to many C-family programmers. All pointer declarations are default initialized to null, so here the first call to writeln prints "null" as the value. The type of p printed in the second writeln is int*. The last line will print 4 in 32-bit and 8 in 64-bit.

So far so good. Now look at the following line and guess what type b is:

int* a, b;

No, b is not an int, it is an int*. The equivalent C or C++ code would look like this:

int *x, *y;

In D, x would be interpreted as...

Left arrow icon Right arrow icon

Key benefits

  • Acquire the skills to understand the fundamentals of D through its support for imperative and object-oriented programming
  • Take advantage of D’s powerful compile-time features, templates and ranges to apply generative, generic, and functional style
  • A systematic guide that will help you become familiar with the concepts in D with the help of simple and easy-to-understand examples

Description

D is a modern programming language that is both powerful and efficient. It combines multiple paradigms in a way that opens up a whole new world of software design. It is used to develop both desktop and web applications, with future targets including mobile, and is available on multiple platforms. It is familiar to anyone with some experience in one or more of the C-family languages. However, hidden in the similarities are several differences that can be surprising when trying to apply common idioms from other languages. When learning D on your own, this can make it more time-consuming to master. In order to make the most of the language and become an idiomatic D programmer, it’s necessary to learn how to think in D. This book familiarizes you with D from the ground up, with a heavy focus on helping you to avoid surprises so that you can take your D knowledge to the next level more quickly and painlessly. Your journey begins with a taste of the language and the basics of compiling D programs with DMD, the reference D compiler developed by Digital Mars, and DUB, a community-developed build utility and package manager. You then set out on an exploration of major language features. This begins with the fundamentals of D, including built-in types, conditionals, loops and all of the basic building-blocks of a D program, followed by an examination of D’s object-oriented programming support. You’ll learn how these features differ from languages you may already be familiar with. Next up are D’s compile-time features, such as Compile-Time Function Evaluation and conditional compilation, then generic programming with templates. After that, you’ll learn the more advanced features of ranges and functional pipeline programming. To enhance your D experience, you are next taken on a tour of the D ecosystem and learn how to make D interact with C. Finally, you get a look at D web development using the vibe.d project and the book closes with some handy advice on where to go next.

Who is this book for?

This book is intended for those with some background in a C-family language who want to learn how to apply their knowledge and experience to D. Perhaps you’re a college student looking to use D for hobby projects, or a career programmer interested in expanding your skillset. This book will help you get up to speed with the language and avoid common pitfalls that arise when translating C-family experience to D.

What you will learn

  • Compile programs with DMD and manage projects with DUB
  • Work efficiently by binding your D programs with new and existing C libraries
  • Generate code at compile-time to enhance runtime performance
  • Implement complex templates for more powerful generic code
  • Write idiomatic D with range-based functional pipelines
  • Use the DUB repository to find a link with a variety of D libraries
  • Implement a web-app in D from the ground up

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 27, 2015
Length: 464 pages
Edition : 1st
Language : English
ISBN-13 : 9781785289347
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 27, 2015
Length: 464 pages
Edition : 1st
Language : English
ISBN-13 : 9781785289347
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 148.97
D Cookbook
$54.99
Learning D
$54.99
D Web Development
$38.99
Total $ 148.97 Stars icon
Banner background image

Table of Contents

12 Chapters
1. How to Get a D in Programming Chevron down icon Chevron up icon
2. Building a Foundation with D Fundamentals Chevron down icon Chevron up icon
3. Programming Objects the D Way Chevron down icon Chevron up icon
4. Running Code at Compile Time Chevron down icon Chevron up icon
5. Generic Programming Made Easy Chevron down icon Chevron up icon
6. Understanding Ranges Chevron down icon Chevron up icon
7. Composing Functional Pipelines with Algorithms and Ranges Chevron down icon Chevron up icon
8. Exploring the Wide World of D Chevron down icon Chevron up icon
9. Connecting D with C Chevron down icon Chevron up icon
10. Taking D Online Chevron down icon Chevron up icon
11. Taking D to the Next Level Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(3 Ratings)
5 star 66.7%
4 star 33.3%
3 star 0%
2 star 0%
1 star 0%
Daniel Kozak Jan 25, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is a really good book. Author explain things in a comprehensible way. If you are interesting in learning a D language and have some basic knowledge in any of similar languages like C++, C, Java, C#.... This book is definitely right for you. If you are already familiar with D ( or even advanced in D same as me :) ) this book will help you to extend your knowledge and clarify them.
Amazon Verified review Amazon
Lance Bachmeier Jan 28, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is an excellent resource for those with some knowledge of the D programming language (Ali Cehreli's book is a better introduction to the language). The chapters are built on examples that are easy to follow, yet provide enough detail to be of use in your own projects. The individual sections are packed with so much information that you'll want to read through them several times.The author is a gifted writer. D programmers are very lucky to have a resource like this available. It's like Knuth decided to write a book on the D programming language.
Amazon Verified review Amazon
Dylan Allbee Jan 25, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
What I love about Michael Parker's treatment of D is that he manages to give an overview which is both comprehensive and understandable. His examples contain only the relevant portions, keeping the focus away from implementation boilerplate. Parker also does a very good job of pointing out potential mistakes to avoid and provides tips for coding idiomaticallyThere are several sections of the book (mostly in the "Taking D to the Next Level" chapter) which should have either received more attention, or simply have been left out.I'd recommend reading this for anyone interested in D with at least some background in programming.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.