writef, compile-checked format, pointer
Patrick Schluter
Patrick.Schluter at bbox.fr
Mon Aug 9 22:01:18 UTC 2021
On Monday, 9 August 2021 at 19:38:28 UTC, novice2 wrote:
> format!"fmt"() and writef!"fmt"() templates
> with compile-time checked format string
> not accept %X for pointers,
>
> but format() and writef() accept it
>
> https://run.dlang.io/is/aQ05Ux
> ```
> void main() {
> import std.stdio: writefln;
> int x;
> writefln("%X", &x); //ok
> writefln!"%s"(&x); //ok
> //writefln!"%X"(&x); //compile error
> }
> ```
>
> is this intentional?
Yes. %X is to format integers. Runtime evaluation of a format
string does not allow for type checking. When using the template,
the evaluation can be thorough and the types can be checked
properly. You have 2 solutions for your problem, either a type
cast
writefln!"%X"(cast(size_t)&x);
or using the generic format specifier that will deduce itself the
format to using depending in the passed type.
writefln!"%s"(&x);
More information about the Digitalmars-d-learn
mailing list