Programming in D – Tutorial and Reference
Ali Çehreli

Other D Resources

Assignment and Order of Evaluation

The first two difficulties that most students face when learning to program involve the assignment operation and the order of evaluation.

The assignment operation

You will see lines similar to the following in almost every program in almost every programming language:

    a = 10;

The meaning of that line is "make a's value become 10". Similarly, the following line means "make b's value become 20":

    b = 20;

Based on that information, what can be said about the following line?

    a = b;

Unfortunately, that line is not about the equality concept of mathematics that we all know. The expression above does not mean "a is equal to b"! When we apply the same logic from the earlier two lines, the expression above must mean "make a's value become the same as b's value".

The well-known = symbol of mathematics has a completely different meaning in programming: make the left side's value the same as the right side's value.

Order of evaluation

In general, the operations of a program are applied step by step in the order that they appear in the program. (There are exceptions to this rule, which we will see in later chapters.) We may see the previous three expressions in a program in the following order:

    a = 10;
    b = 20;
    a = b;

The meaning of those three lines altogether is this: "make a's value become 10, then make b's value become 20, then make a's value become the same as b's value". Accordingly, after those three operations are performed, the value of both a and b would be 20.

Exercise

Observe that the following three operations swap the values of a and b. If at the beginning their values are 1 and 2 respectively, after the operations the values become 2 and 1:

    c = a;
    a = b;
    b = c;