www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Implicit integer conversions Before Preconditions

reply jmh530 <john.michael.hall gmail.com> writes:
In the code below, `x` and `y` are implicitly converted to `uint` 
and `ushort` before the function preconditions are run.

Is there any way to change this behavior? It feels unintuitive 
and I can't find in the spec where it says when the conversions 
in this case occur, but it clearly happens before the 
preconditions are run.

```d
import std.stdio: writeln;

void foo(uint x)
     in (x >= 0)
{
     writeln(x);
}

void foo(ushort x)
     in (x >= 0)
{
     writeln(x);
}

void main() {
     int x = -1;
     foo(x); //prints 4294967295
     short y = -1;
     foo(y); //prints 65535
}
```
May 24 2022
parent reply Steven Schveighoffer <schveiguy gmail.com> writes:
On 5/24/22 4:46 PM, jmh530 wrote:
 In the code below, `x` and `y` are implicitly converted to `uint` and 
 `ushort` before the function preconditions are run.
 
 Is there any way to change this behavior? It feels unintuitive and I 
 can't find in the spec where it says when the conversions in this case 
 occur, but it clearly happens before the preconditions are run.
 
 ```d
 import std.stdio: writeln;
 
 void foo(uint x)
      in (x >= 0)
 {
      writeln(x);
 }
 
 void foo(ushort x)
      in (x >= 0)
 {
      writeln(x);
 }
 
 void main() {
      int x = -1;
      foo(x); //prints 4294967295
      short y = -1;
      foo(y); //prints 65535
 }
 ```
```d // e.g. foo(int x) in (x >= 0) { return foo(uint(x)); } ``` And remove those useless `in` conditions on the unsigned versions, an unsigned variable is always >= 0. -Steve
May 24 2022
parent jmh530 <john.michael.hall gmail.com> writes:
On Tuesday, 24 May 2022 at 21:05:00 UTC, Steven Schveighoffer 
wrote:
 [snip]

 ```d
 // e.g.
 foo(int x)
 in (x >= 0)
 {
    return foo(uint(x));
 }
 ```

 And remove those useless `in` conditions on the unsigned 
 versions, an unsigned variable is always >= 0.

 -Steve
Thanks. That makes perfect sense. I just got thrown by the preconditions not running first.
May 24 2022