Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Basics and Types

Integers and Floating-Point Numbers in D

Understand D's signed and unsigned integers, silent wrap-around on overflow, integer division, floating-point precision, NaN and infinity, and how to compare numbers safely.

Numbers look simple until the edges: a counter that wraps around, a division that drops the remainder, a sum of decimals that is not exactly right. This lesson explains how D's integer and floating-point types behave at those edges, which checks D gives you, and which you must add yourself. The D listings are read-only; the C stand-ins use the same fixed-size types so the results match.

Integer types and literals

D has eight integer types: byte, short, int, long (signed) and ubyte, ushort, uint, ulong (unsigned). A decimal literal is an int if it fits and a long otherwise; a u suffix makes it unsigned and L makes it long:

D
auto a = 100;       // int
auto b = 100u;      // uint
auto c = 100L;      // long
auto d = 100UL;     // ulong
auto e = 0xFF;      // 255
auto f = 0b1111_0000; // 240
auto g = 1_000_000; // underscores are ignored

Use int unless you have a reason. Use ulong or long for sizes and counts that might exceed two billion, and the size_t alias (a ulong on 64-bit systems) for array lengths and indexes.

Overflow wraps around

D integers do not trap on overflow. When a result does not fit, the extra high bits are dropped, which is the same as arithmetic modulo 2^n:

D
import std.stdio;

void main()
{
    int big = int.max;
    big++;
    writeln(big);          // -2147483648

    ubyte b = 250;
    b += 10;
    writeln(b);            // 4

    uint zero = 0;
    zero--;
    writeln(zero);         // 4294967295
}

For code where overflow would be a bug, use core.checkedint (adds, muls) or std.experimental.checkedint, which flag the overflow. Never rely on wrap-around of signed values being "defined" in portable thinking: D does define it as two's complement, but results are usually surprising.

Integer division and remainder

Dividing two integers gives an integer; the fraction is discarded toward zero. % gives the remainder, with the sign of the left operand:

D
writeln(7 / 2);        // 3
writeln(-7 / 2);       // -3
writeln(7 % 2);        // 1
writeln(-7 % 2);       // -1
writeln(7.0 / 2);      // 3.5

To get a fractional result, make at least one operand floating-point. Dividing an integer by zero raises a hardware exception and stops the program, so guard divisors you do not control.

Floating-point types

float (32 bits), double (64 bits) and real (the widest the hardware offers, often 80 bits on x86) store numbers in binary scientific notation. double is the default for literals like 2.5. They cannot represent most decimals exactly:

D
import std.stdio;
import std.math : isClose, isNaN, isInfinity;

void main()
{
    double sum = 0.1 + 0.2;
    writeln(sum == 0.3);              // false
    writeln(isClose(sum, 0.3));       // true
    writefln("%.20f", sum);           // 0.30000000000000004441

    double zero = 0.0;
    writeln(1.0 / zero);              // inf
    writeln((zero / zero).isNaN);     // true
}

Never compare floating-point results with == after arithmetic; use isClose (or compare with an explicit tolerance). Division by zero in floating point does not crash: it gives inf or nan. Any comparison with nan is false, including nan == nan, which is why you test with isNaN.

Use double by default. Use float only for large arrays where memory matters, or when a graphics API demands it. Use real for extra precision in numeric code if you accept that it is slower and platform-dependent.

Bitwise operators

Integers support &, |, ^, ~ (complement), <<, >> (arithmetic shift for signed) and >>> (logical shift). 1 << 4 is 16. Shifting by an amount greater than or equal to the bit width is an error for constants and undefined at run time, so keep shifts in range.

C stand-ins: wrap-around and rounding

The same machine rules apply in C with fixed-width types, so you can see the results.

C C stand-in: wrap-around with fixed-width types

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 is ubyte: 4, uint: 4294967295 and int.max + 1 wraps to -2147483648. Notice the caveat in the code comment: C leaves signed overflow undefined, whereas D defines it as wrapping.

C C stand-in: decimals are not exact

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.

You will see 0 for the exact comparison, 1 for the tolerance test, the long decimal expansion 0.30000000000000004441, and the integer results 3, -3, 1, -1.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when a D int exceeds int.max?

    D integer arithmetic does not trap; the extra bits are discarded.
  2. 2. What is -7 / 2 in D?

    Integer division truncates toward zero.
  3. 3. Why should you avoid == on floating-point results?

    Use isClose or a tolerance.
  4. 4. What does 1.0 / 0.0 give in D?

    Floating-point division by zero gives infinity.
  5. 5. Which suffix makes a literal unsigned long?

    100UL is a ulong; U alone gives uint.

Summary

  • D's integer types have fixed sizes; literals are int or long by size, with u and L suffixes.
  • Overflow wraps silently; use checked arithmetic where it matters.
  • Integer division truncates; make an operand floating-point for fractions.
  • Compare floats with isClose, test nan with isNaN, and expect inf from division by zero.

Next: Characters and strings