BetterC, int to string?
jfondren
julian.fondren at gmail.com
Fri Jun 18 09:32:04 UTC 2021
On Friday, 18 June 2021 at 09:05:38 UTC, Mike Brown wrote:
> Hi all,
>
> I would like to convert a D string to an int - im doing this in
> a compile time function as well. conv throws an error due to it
> using TypeInfo?
>
> How would I do this?
>
> Kind regards,
> Mike
BetterC has [some CTFE-related
bugs](https://issues.dlang.org/buglist.cgi?f1=keywords&list_id=236535&o1=allwordssubstr&query_format=advanced&resolution=---&v1=betterC%20CTFE) atm that might be the problem here.
You could if you need betterC use libc at runtime,
```d
extern (C) void main() {
import core.stdc.stdlib : atoi;
import core.stdc.stdio : printf;
const n = atoi("123"); // not enum
printf("%d\n", n);
}
```
or if you're more concerned about limiting the GC, you can use
@nogc annotations for that while still having more of the
language at CTFE and elsewhere:
```d
void main() @nogc nothrow {
import core.stdc.stdio : printf;
import std.conv : to;
enum n = to!int("123"); // not const
printf("%d\n", n);
}
```
If `n` were const in that last example:
```
exmaple.d(5): Error: `@nogc` function `D main` cannot call
non- at nogc function `std.conv.to!int.to!string.to`
example.d(5): Error: function `std.conv.to!int.to!string.to` is
not `nothrow`
example.d(1): Error: `nothrow` function `D main` may throw
```
More information about the Digitalmars-d-learn
mailing list