Chuyển đến nội dung

Bài 9 · Basics and Types

Operators, Expressions and Enums in D

A tour of D's operators: arithmetic, comparison, logical, bitwise, the power and concatenation operators, in, is, the ternary operator, precedence rules, and named enums.

An expression combines values with operators to produce a new value. D keeps C's familiar operator set and adds a handful of its own: ^^ for powers, ~ for concatenation, in for membership, is for identity, and !is. This lesson lists them, explains precedence and short-circuiting, and ends with enums, D's way of naming a set of constants. The D code is read-only; C stand-ins model precedence and bit flags.

Arithmetic and assignment

Operator Meaning Example Result
+ - * / basic arithmetic 7 + 2 * 3 13
% remainder 17 % 5 2
^^ power 2 ^^ 10 1024
++ -- increment, decrement ++i add 1 first
+= -= *= /= %= ^^= ~= compound assignment x *= 3 x = x * 3

^^ is right-associative and works on integers and floating point: 2 ^^ 3 ^^ 2 is 2 ^^ 9, which is 512. The compound ~= appends to arrays and strings.

Comparison and logic

==, !=, <, <=, >, >= compare values. D adds is and !is, which compare identity: a is b is true when two references (or pointers, or slices) refer to exactly the same thing, and x is null is the proper null test. &&, || and ! are the logical operators; && and || short-circuit, so the right side runs only when needed:

D
import std.stdio;

bool check(string label, bool value)
{
    writeln("checking ", label);
    return value;
}

void main()
{
    if (check("A", false) && check("B", true))
    {
        writeln("both");
    }
    // prints only: checking A
}

Bitwise operators and shifts

&, |, ^, ~x, <<, >> and >>> work on integers. They are the basis of flag fields and masks:

D
uint flags = 0;
flags |= 0b0001;            // set bit 0
flags |= 0b0100;            // set bit 2
flags &= ~0b0001;           // clear bit 0
bool hasBit2 = (flags & 0b0100) != 0;   // true

Always put parentheses around a bitwise test, because & binds more loosely than == in C-style precedence. D goes further than C: it makes a & b == c an error and asks you to add parentheses, which removes a famous trap.

The in operator and the ternary

in tests whether a key exists in an associative array and returns a pointer to the value, or null:

D
int[string] stock = ["apple": 3, "pear": 0];
if (auto p = "apple" in stock)
{
    writeln("apple: ", *p);      // apple: 3
}
string label = stock["pear"] > 0 ? "available" : "sold out";   // ternary

cond ? a : b picks one of two expressions. Use it for simple choices; nest it sparingly.

Precedence at a glance

From tightest to loosest binding: postfix (., [], ()), ^^, unary (!, ~, -, ++), * / %, + - ~ (binary), shifts, comparisons and in/is, &, ^, |, &&, ||, ?:, assignments. When in doubt, add parentheses: they cost nothing and make intent obvious.

flowchart TD
    A["postfix . [] ()"] --> B["^^ power"]
    B --> C["unary ! ~ -"]
    C --> D["* / %"]
    D --> E["+ - ~"]
    E --> F["comparison, in, is"]
    F --> G["& ^ |"]
    G --> H["&& ||"]
    H --> I["?: and assignment"]

Operators higher in the diagram bind more tightly.

Enums: named constants

An enum groups related values under names and makes switch statements checkable:

D
enum Color { red, green, blue }          // 0, 1, 2

enum Level : ubyte                       // choose the underlying type
{
    low = 1,
    mid = 5,
    high = 10
}

void main()
{
    import std.stdio, std.conv : to;
    Color c = Color.green;
    writeln(c);                  // green
    writeln(cast(int) c);        // 1
    writeln(Level.mid + 1);      // 6
    writeln("blue".to!Color);    // blue
}

writeln prints the member name, to!Color parses a name back into the enum, and Color.max and Color.min give the extremes. An anonymous enum (enum { a = 1, b = 2 }) defines plain constants, and enum x = 42; defines a single manifest constant, as seen in Variables, types and initialization.

C stand-ins: precedence and flags

C C stand-in: precedence needs parentheses

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output shows 13, 27, 1024, then 1 and 1. The unparenthesized flags & 4 == 4 is read as flags & (4 == 4), which is flags & 1; it happens to give 1 here but gives the wrong answer for other values. D rejects that line at compile time.

C C stand-in: bit flags and an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints rw-, r-- and r-x: set with |=, clear with &= ~, test with &.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is 2 ^^ 3 in D?

    ^^ is the power operator.
  2. 2. What does x is null test?

    is compares identity; x is null checks for a null reference or pointer.
  3. 3. What does key in assocArray return?

    in yields a pointer so you can test and use the value in one step.
  4. 4. Why does D reject a & b == c without parentheses?

    The compiler asks you to be explicit about grouping.

Summary

  • D has C's operators plus ^^, ~, in and is.
  • && and || short-circuit; is compares identity.
  • Parenthesize bit tests; D turns ambiguous ones into errors.
  • enum names constants and can pick an underlying type.

Next: Conditionals: if, else and switch

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.