www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - Typedef arithmetic

Using DMD 0.121, Windows 98SE.

When typedef'd values are arithmetically combined, what should be the 
type of the result?

Take this:

----------
import std.stdio;

typedef int Int1;
typedef int Int2;

void show(Int1 v) {
     writefln("Int1: %d", v);
}

void show(Int2 v) {
     writefln("Int2: %d", v);
}

void show(int i) {
     writefln("int: %d", i);
}

void show(long l) {
     writefln("long: %d", l);
}

void main() {
     Int1 value1 = 42;
     Int2 value2 = 69;

     show(value1 + value2);
     show(value2 + value1);
     show(2 * value1);
     show(value1 * 2);
     show(value1 + value1);
     show(value2 - value2);
     show(value1 + 2);
     show(3 + value2);

     long l = 23;
     show(value1 + l);
     show(l + value2);

     short s = 105;
     show(s + value1);
     show(value2 + s);
}
----------
Int1: 111
Int2: 111
int: 84
Int1: 84
Int1: 84
Int2: 0
Int1: 44
int: 72
long: 65
long: 92
int: 147
Int2: 174
----------

What seems to be happening is that the result takes the type of the left 
operand.  Unless of course promotion changes the type of this operand.

But this doesn't seem right to me.  The essence of typedefs is that the 
types might not be value-compatible in terms of the semantics the 
programmer has given the types.  And so it doesn't make sense for the 
compiler to assume that the result is going to be compatible with one of 
the types.

The spec gives no indication (that I can see) of how it's supposed to 
work.  But here's how I feel it should work:

- If the operands are of the same types, the result will be of the same 
type.
- If a typedef is combined with its base type, the result will be of the 
base type.  (This would apply to typedef chains of any length.)
- If two typedefs with a common base type are combined, the result will 
be of the common base type.
- If there is no common base type, the standard promotion rules apply 
and the result is of a built-in type.

Stewart.

-- 
My e-mail is valid but not my primary mailbox.  Please keep replies on 
the 'group where everyone may benefit.
Apr 29 2005