Automatic Type Conversions
Let’s learn about automatic type conversions and integer promotions.
We'll cover the following...
Variables must be compatible with the expressions that they take part in. As it has probably been obvious from the programs that we have seen so far, D is a statically typed language, meaning that the compatibility of types is validated at compile time.
All of the expressions that we have written so far always had compatible types because otherwise the code would be rejected by the compiler. The following is an example of code that has incompatible types:
import std.stdio;void main() {char[] slice;writeln(slice + 5); // ← compilation ERROR}
The compiler rejects the code due to the incompatible types char[]
and int
for the addition operation.
Type incompatibility does not mean that the types are different; different types can indeed be used in expressions safely. For example, an int
variable can safely be ...