Programming in D Ali Çehreli Programming in D First Edition Ali Çehreli Edited by Luís Marques Programming in D, First Edition Revision:2015-12-111 The most recent electronic versions of this book are availableonline2. Copyleft (ɔ) 2009-2015 Ali Çehreli This work is licensed under the Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. Edited byLuís Marques3 Cover design byİzgi Yapıcı4 Cover illustration bySarah Reece5 Published byAli Çehreli6 Fonts: Andada by Carolina Giovagnoli for Huerta Tipográfica Open Sans by Steve Matteson DejaVu Mono by DejaVu Fonts PDF version is generated with Prince XML Other ebook versions are generated with Calibre ISBNs: 978-0-692-59943-3 hardcover by IngramSpark 978-0-692-52957-7 paperback by IngramSpark 978-1-515-07460-1 paperback by CreateSpace 978-1-519-95441-1 ePUB by Draft2Digital 1. https://bitbucket.org/acehreli/ddili 2. http://ddili.org/ders/d.en 3. http://www.luismarques.eu 4. http://izgiyapici.com 5. mailto:[email protected] 6. mailto:[email protected] Contents Forewordby Andrei Alexandrescu xvii Preface xix Acknowledgments.............................................................................................................xix 1.The Hello World Program 1 Compiler installation............................................................................................................1 Source file...................................................................................................................................1 Compiling the hello world program...............................................................................1 Compiler switches.................................................................................................................2 IDE................................................................................................................................................3 Contents of the hello world program............................................................................3 Exercises....................................................................................................................................4 2.writelnandwrite 5 Exercises....................................................................................................................................5 3.Compilation 6 Machine code..........................................................................................................................6 Programming language.......................................................................................................6 Interpreter................................................................................................................................6 Compiler....................................................................................................................................7 4.Fundamental Types 8 Properties of types.................................................................................................................9 size_t......................................................................................................................................10 Exercise....................................................................................................................................10 5.Assignment and Order of Evaluation 11 The assignment operation................................................................................................11 Order of evaluation..............................................................................................................11 Exercise.....................................................................................................................................11 6.Variables 12 Exercise....................................................................................................................................13 7.Standard Input and Output Streams 14 Exercise....................................................................................................................................14 8.Reading from the Standard Input 15 Skipping the whitespace characters............................................................................16 Additional information.....................................................................................................17 Exercise....................................................................................................................................17 9.Logical Expressions 18 Logical Expressions.............................................................................................................18 Grouping expressions........................................................................................................21 Readingboolinput.............................................................................................................21 Exercises..................................................................................................................................22 10.ifStatement 24 Theifblock and its scope...............................................................................................24 Theelseblock and its scope..........................................................................................24 Always use the scope curly brackets............................................................................25 The "if, else if, else" chain..................................................................................................25 Exercises..................................................................................................................................27 11.whileLoop 28 Thecontinuestatement..................................................................................................28 Thebreakstatement..........................................................................................................29 v Infinite loop............................................................................................................................29 Exercises..................................................................................................................................30 12.Integers and Arithmetic Operations 31 Exercises.................................................................................................................................40 13.Floating Point Types 42 Floating point type properties........................................................................................42 .nan...........................................................................................................................................43 Specifying floating point values....................................................................................43 Overflow is not ignored.....................................................................................................44 Precision..................................................................................................................................45 There is no truncation in division................................................................................45 Which type to use................................................................................................................46 Cannot represent all values.............................................................................................46 Comparing floating point values...................................................................................47 Exercises..................................................................................................................................48 14.Arrays 49 Definition................................................................................................................................49 Containers and elements..................................................................................................50 Accessing the elements......................................................................................................50 Index..........................................................................................................................................51 Fixed-length arrays vs. dynamic arrays......................................................................51 Using.lengthto get or set the number of elements............................................51 An array example................................................................................................................52 Initializing the elements...................................................................................................52 Basic array operations.......................................................................................................53 Exercises..................................................................................................................................55 15.Characters 56 History......................................................................................................................................56 Unicode encodings..............................................................................................................57 The character types of D...................................................................................................58 Character literals.................................................................................................................58 Control characters...............................................................................................................59 Single quote and backslash.............................................................................................59 The std.uni module............................................................................................................60 Limited support for ı and i...............................................................................................61 Problems with reading characters...............................................................................61 D's Unicode support............................................................................................................62 Summary.................................................................................................................................63 16.Slices and Other Array Features 64 Slices..........................................................................................................................................64 Using$, instead ofarray.length................................................................................65 Using.dupto copy..............................................................................................................65 Assignment.............................................................................................................................66 Making a slice longer may terminate sharing.........................................................66 Operations on all elements..............................................................................................69 Multi-dimensional arrays................................................................................................71 Summary.................................................................................................................................72 Exercise....................................................................................................................................73 17.Strings 74 readlnandstrip, instead ofreadf...........................................................................74 formattedReadfor parsing strings.............................................................................75 vi Double quotes, not single quotes...................................................................................76 string,wstring, anddstringare immutable......................................................76 Potentially confusing length of strings.......................................................................77 String literals.........................................................................................................................78 String concatenation..........................................................................................................78 Comparing strings...............................................................................................................79 Lowercase and uppercase are different......................................................................79 Exercises.................................................................................................................................80 18.Redirecting the Standard Input and Output Streams 81 Redirecting the standard output to a file with operator>..................................81 Redirecting the standard input from a file with operator<..............................81 Redirecting both standard streams..............................................................................82 Piping programs with operator|..................................................................................82 Exercise....................................................................................................................................82 19.Files 83 Fundamental concepts......................................................................................................83 std.stdio.Filestruct.....................................................................................................85 Exercise....................................................................................................................................86 20.autoandtypeof 87 auto...........................................................................................................................................87 typeof......................................................................................................................................87 Exercise....................................................................................................................................88 21.Name Scope 89 Defining names closest to their first use....................................................................89 22.forLoop 91 The sections of thewhileloop.......................................................................................91 The sections of theforloop............................................................................................91 The sections may be empty.............................................................................................92 The name scope of the loop variable...........................................................................93 Exercises..................................................................................................................................93 23.Ternary Operator?: 94 The type of the ternary expression..............................................................................95 Exercise....................................................................................................................................96 24.Literals 97 Integer literals.......................................................................................................................97 Floating point literals.........................................................................................................99 Character literals.................................................................................................................99 String literals......................................................................................................................100 Literals are calculated at compile time.....................................................................101 Exercises................................................................................................................................101 25.Formatted Output 103 format_character................................................................................................................104 width........................................................................................................................................106 precision..................................................................................................................................106 flags..........................................................................................................................................107 Positional parameters......................................................................................................108 Formatted element output.............................................................................................109 format....................................................................................................................................110 Exercises................................................................................................................................110 vii 26.Formatted Input 111 Format specifier characters...........................................................................................112 Exercise..................................................................................................................................112 27.do-whileLoop 113 Exercise..................................................................................................................................114 28.Associative Arrays 115 Definition...............................................................................................................................115 Adding key-value pairs....................................................................................................116 Initialization........................................................................................................................116 Removing key-value pairs..............................................................................................116 Determining the presence of a key.............................................................................117 Properties..............................................................................................................................117 Example.................................................................................................................................118 Exercises................................................................................................................................118 29.foreachLoop 119 Theforeachsyntax..........................................................................................................119 continueandbreak........................................................................................................120 foreachwith arrays.........................................................................................................120 foreachwith strings andstd.range.stride.....................................................120 foreachwith associative arrays.................................................................................121 foreachwith number ranges......................................................................................121 foreachwith structs, classes, and ranges...............................................................121 The counter is automatic only for arrays................................................................122 The copy of the element, not the element itself....................................................122 The integrity of the container must be preserved...............................................123 foreach_reverseto iterate in the reverse direction.........................................123 Exercise..................................................................................................................................123 30.switchandcase 125 Thegotostatement...........................................................................................................125 The expression must be an integer, string, orbooltype..................................127 Value ranges.........................................................................................................................128 Distinct values.....................................................................................................................128 Thefinal switchstatement......................................................................................128 When to use..........................................................................................................................129 Exercises................................................................................................................................129 31.enum 130 Effects of magic constants on code quality.............................................................130 Theenumsyntax.................................................................................................................130 Actual values and base types.........................................................................................131 enumvalues that are not of anenumtype..................................................................131 Properties..............................................................................................................................132 Converting from the base type.....................................................................................133 Exercise..................................................................................................................................133 32.Functions 134 Parameters............................................................................................................................135 Calling a function..............................................................................................................137 Doing work...........................................................................................................................137 The return value.................................................................................................................137 Thereturnstatement.....................................................................................................138 voidfunctions....................................................................................................................138 viii The name of the function...............................................................................................139 Code quality through functions...................................................................................139 Exercises................................................................................................................................143 33.Immutability 145 Immutable variables........................................................................................................145 Immutable parameters....................................................................................................148 Immutability of the slice versus the elements.......................................................152 How to use............................................................................................................................153 Summary...............................................................................................................................154 34.Value Types and Reference Types 155 Value types............................................................................................................................155 Reference variables...........................................................................................................156 Reference types...................................................................................................................157 Fixed-length arrays are value types, slices are reference types......................161 Experiment...........................................................................................................................161 Summary...............................................................................................................................163 35.Function Parameters 164 Parameters are always copied......................................................................................164 Referenced variables are not copied..........................................................................165 Parameter qualifiers.........................................................................................................167 Summary...............................................................................................................................175 Exercise..................................................................................................................................176 36.Lvalues and Rvalues 177 Limitations of rvalues......................................................................................................177 Usingauto refparameters to accept both lvalues and rvalues..................178 Terminology.........................................................................................................................179 37.Lazy Operators 180 38.Program Environment 181 The return value ofmain()...........................................................................................181 Standard error streamstderr.....................................................................................183 Parameters ofmain()......................................................................................................183 Command line options and thestd.getoptmodule........................................184 Environment variables....................................................................................................186 Starting other programs.................................................................................................186 Summary...............................................................................................................................187 Exercises................................................................................................................................187 39.Exceptions 188 Thethrowstatement to throw exceptions..............................................................188 Thetry-catchstatement to catch exceptions.....................................................193 Exception properties........................................................................................................198 Kinds of errors....................................................................................................................199 Summary...............................................................................................................................201 40.scope 202 41.assertandenforce 204 Syntax....................................................................................................................................204 static assert.................................................................................................................205 asserteven ifabsolutely true.......................................................................................206 No value nor side effect..................................................................................................206 Disablingassertchecks...............................................................................................207 enforcefor throwing exceptions..............................................................................207 ix How to use...........................................................................................................................207 Exercises...............................................................................................................................208 42.Unit Testing 210 Causes of bugs.....................................................................................................................210 Discovering the bugs........................................................................................................210 Unit testing for catching bugs......................................................................................211 Activating the unit tests..................................................................................................212 unittestblocks.................................................................................................................212 Testing for exceptions......................................................................................................213 Test driven development.................................................................................................214 Exercise..................................................................................................................................216 43.Contract Programming 217 inblocks for preconditions...........................................................................................217 outblocks for postconditions......................................................................................218 Disabling contract programming..............................................................................220 inblocks versusenforcechecks...............................................................................220 Exercise..................................................................................................................................221 44.Lifetimes and Fundamental Operations 223 Lifetime of a variable.......................................................................................................223 Lifetime of a parameter..................................................................................................223 Fundamental operations...............................................................................................224 45.ThenullValue and theisOperator 228 Thenullvalue...................................................................................................................228 Theisoperator.................................................................................................................229 The!isoperator...............................................................................................................229 Assigning thenullvalue...............................................................................................229 Summary..............................................................................................................................230 46.Type Conversions 232 Automatic type conversions.........................................................................................232 Explicit type conversions................................................................................................237 Summary..............................................................................................................................240 47.Structs 241 Definition..............................................................................................................................241 Accessing the members..................................................................................................243 Construction.......................................................................................................................244 Copying and assignment...............................................................................................246 Struct literals......................................................................................................................248 staticmembers...............................................................................................................248 Exercises................................................................................................................................251 48.Variable Number of Parameters 253 Default arguments............................................................................................................253 Variadic functions.............................................................................................................255 Exercise.................................................................................................................................258 49.Function Overloading 260 Overload resolution..........................................................................................................261 Function overloading for user-defined types.........................................................261 Limitations..........................................................................................................................262 Exercise.................................................................................................................................263 50.Member Functions 264 Defining member functions.........................................................................................264 x