Compile time int to string conversion in BetterC

Steven Schveighoffer schveiguy at gmail.com
Wed Aug 17 11:38:31 UTC 2022


On 8/17/22 6:38 AM, Dennis wrote:
> On Wednesday, 17 August 2022 at 08:44:30 UTC, Ogi wrote:
>> Maybe I’m missing something?
> 
> I had the same problem, and came up with the following trick:
> 
> ```D
> enum itoa(int i) = i.stringof;
> ```

I have the same thing in my code:

```d
enum intStr(int x) = x.stringof;
```

The reason you do this is to shoehorn things that aren't technically 
ints (such as enum types) into ints. This avoids weirdness like 
`cast(foo)bar` or whatnot that might happen if you just use stringof on 
any expression.

> 
> Now I need to warn you that the output of `stringof` is technically 
> implementation defined per the specification, so you shouldn't rely on 
> it. In practice [this doesn't stop 
> people](https://github.com/libmir/mir-algorithm/pull/422), and I don't 
> think integers will ever not be printed as a string of base 10 digits.

Yeah, I wouldn't worry about stringof for ints.

-Steve


More information about the Digitalmars-d-learn mailing list