Using the exponentiation operator
D has a built-in exponentiation operator: the ^^
operator.
How to do it…
In order to use the exponentiation operator, we need to execute the following steps:
Write an expression with the
^^
operator.Make one or both arguments floating point if you want a floating point result.
The code is as follows:
int a = 2^^3; // a == 8 float b = 2.0 ^^ 3.0; // b == 8.0 auto c = 2 * 2 ^^ 3; // c == 16
How it works…
The exponentiation operator is first subject to constant folding and is then rewritten into a call to the std.math.pow
library function to perform the operation. The result follows the regular arithmetic type rules of the D language, so the int
arguments yield an int
result and the float
arguments yield a float
result.
The operator also follows the usual arithmetic order of operations, so it has higher precedence than multiplication, as seen in the third example line.
The choice of ^^
for the operator was driven by the desire: to look like ASCII math without being confusing in the context of the D programming language. The two other major competitors, ^
and **
, were rejected because they conflict with existing operations inherited by C: ^
is the bitwise XOR operator in both C and D, while **
is currently parsed as multiplication of a dereferenced pointer. While the lexer could be changed to make it into a new operator, this could potentially lead to silent breakages when porting C code to D, which D tries to avoid. (D doesn't mind breaking C code, but it prefers it to be a compile error whenever possible instead of code that compiles the same then acts differently.)
Thus, ^^
was chosen, and it is visually similar to how exponentiation is often written in ASCII text (2^3
for example), without being in conflict with any existing C or D code.
Note
Why isn't ^^
used for Boolean XOR in the same way that ||
is Boolean OR and &&
is Boolean AND? It is because Boolean XOR already has an operator: !=
. If you write out the truth tables for is-not-equal, you'll find they are an exact match for a hypothetical Boolean XOR!