More on semantics of opPow: return type

Simen kjaeraas simen.kjaras at gmail.com
Mon Dec 7 04:59:04 PST 2009


On Mon, 07 Dec 2009 13:13:34 +0100, Don <nospam at nospam.com> wrote:

> As has been mentioned in previous posts, a ^^ b should be right  
> associative and have a precedence between multiplication and unary  
> operators. That much is clear.
>
>
> Operations involving integers are far less obvious (and are actually  
> where a major benefit of an operator can come in).
>
> Using the normal promotion rules, 10^^2 is an integer. The range  
> checking already present in D2 could be extended so that the compiler  
> knows it'll even fit in a byte. This gets rid of one of the classic  
> annoyances of C pow:  int x = pow(2, 10); doesn't compile without a cast.
>
> But the difficult question is, what's the type of 10^^-2 ? Should it be  
> an error? (since the result, 0.01, is not representable as an integer).  
> Should it return zero? (just as 1/2 doesn't return 0.5). For an example  
> of these semantics, see http://www.tcl.tk/cgi-bin/tct/tip/123.html).
> Or should it return a double?
> Or should 10^^2 also be a double, but implicitly castable to byte  
> because of the range checking rules?
>
> I currently favour making it an error, so that the normal promotion  
> rules apply. It seems reasonable to me to require a cast to floating  
> point in there somewhere.
> This is analagous to the similar case f ^^ 0.1; where f is known to be  
> negative. This gives a complex result, creating a run-time error  
> (returns a NaN). But, there's no standard error and no NaNs for integer  
> underflow.
>
> One could also make int ^^ uint defined (returning an int), but not int  
> ^^ int. Again thanks to range checking, int ^^ uint ^^ uint would work,  
> because although uint ^^ uint is an int, it's known to be positive, so  
> would implicitly convert to int. But would making int ^^ int illegal,  
> make it too much of an annoying special case?
>
> I strongly suspect that x^^y, where x and y are integers, and the value  
> of y is not known at compile time, is an extremely rare operation.
>
> Also, should int^^uint generate some kind of overflow error? Although  
> other arithmeic integer operators don't, it's fantastically easy to hit  
> an overflow with x^^y. Unless x is 1, y must be tiny (< 64 to avoid  
> overflowing a ulong).

I believe int^^int should not be defined (it's basically useless, as one
would (almost) always want an integer result, and a float result could
easily be had by casting).

As regards n^^(x >= n.sizeof * 8), I'm not 100% sure. I'm leaning towards
only allowing int^^ubyte, but it seems constraining.

-- 
Simen



More information about the Digitalmars-d mailing list