...

/

Return Types of Operators

Return Types of Operators

Learn about the return types of operators.

We'll cover the following...

When overloading an operator, it is advisable to observe the return type of the same operator on fundamental types. This will help in making sense of the code and reducing confusion.

None of the operators on fundamental types return void. This fact should be obvious for some operators. For example, the result of adding two int values as a + b is int:

Press + to interact
import std.stdio;
void main() {
int a = 1;
int b = 2;
int c = a + b; // c gets initialized by the return value
// of the + operator
writeln(c);
}

The return values of some other operators may not be so obvious. For example, even operators like ++i have values:

Press + to interact
import std.stdio;
void main() {
int i = 1;
writeln(++i); // prints 2
}

The ++ operator not only increments i, it also produces the new value of i. Furthermore, the value that is produced by ++ is not just the new value of i, rather it is the variable i itself. You can see this by printing the address of the result of that expression:

Press + to interact
import std.stdio;
void main() {
int i = 1;
writeln("The address of i : ", &i);
writeln("The address of the result of ++i: ", &(++i));
}

The output contains identical addresses.

Guidelines for

...