Home > Articles > Programming > Ruby

  • Print
  • + Share This
From the book

1.2 Statements

In D, just like in its sibling languages, any expression followed by a semicolon is a statement (for example, the sample program's call to writefln has a ';' appended). The effect of the statement is to simply evaluate the expression.

D is a member of the "curly-braces block scoped" family, meaning that you can group several statements into one by surrounding them with '{' and '}'—something necessary, for example, when you want to do several things inside a foreach loop. In the case of exactly one statement, you can omit the curly braces entirely. In fact, our entire height conversion double loop could be rewritten as follows:

foreach (feet; 5 .. 7)
  foreach (inches; 0 .. inchperfoot)
    writefln("%s'%s''\t%s", feet, inches,
    (feet * inchperfoot + inches) * cmperinch);

Omitting braces for single statements has the advantage of shorter code and the disadvantage of making edits more fiddly (during code maintenance, you'll need to add or remove braces as you mess with statements.) People tend to get pretty divided when it comes about rules for indentation and for placing curly braces. In fact, so long as you're consistent, these things are not as important as they might seem, and as a proof, the style used in this book (full bracing even for single statements, opening braces on the introducing line, and closing braces on their own lines) is, for typographical reasons, quite different from the author's style in everyday code. If he could do this without turning into a werewolf beyond all reasonable doubt, so could anyone.

The Python language made popular a different style of expressing block structure by means of indentation—"form follows structure" at its best. Whitespace that matters is an odd proposition for programmers of some other languages, but Python programmers swear by it. D normally ignores whitespace, but is especially designed to be easily parsed (e.g. parsing does not need to understand the meaning of symbols), which suggests that a nice pet project could implement a simple preprocessor allowing usage of Python indentation style with D without suffering any inconvenience in the process of compiling, running, and debugging programs.

Finally, the code samples above already introduced the if statement. The general form should be very familiar:

if (expression) statement1 else statement2

A nice theoretical result known as the theorem of structure [1] proves that we can implement any algorithm using compound statements, if tests, and loops à la for and foreach. Of course any realistic language would offer more than just that, and D is no exception, but for now let's declare ourselves content as far as statements go, and move on.

  • + Share This
  • 🔖 Save To Your Account