Am Mon, 01 Oct 2012 13:22:46 +0200 schrieb Piotr Szturmaj <bncr...@jadamspam.pl>:
> Paulo Pinto wrote: > > On Monday, 1 October 2012 at 09:42:08 UTC, Piotr Szturmaj wrote: > >> Jakob Ovrum wrote: > >>> On Monday, 1 October 2012 at 09:17:52 UTC, Piotr Szturmaj wrote: > >>>> Adam D. Ruppe wrote: > >>>>> On Saturday, 29 September 2012 at 02:11:12 UTC, Alex Rønne > >>>>> Petersen wrote: > >>>>> Also this reminds me of the utter uselessness of the current > >>>>> behavior of > >>>>> "%s" and a pointer - it prints the address. > >>>> > >>>> Why not specialize current "%s" for character pointer types so > >>>> it will print null terminated strings? It's always possible to > >>>> cast to void* to print an address. > >>> > >>> It's not safe to assume that pointers to characters are generally > >>> null terminated. > >> > >> Yes, but programmer should know what he's passing anyway. > > > > The thinking "the programmer should" only works in one man teams. > > > > As soon as you start having teams with disparate programming > > knowledge among team members, you can forget everything about "the > > programmer should". > > I experienced such team at my previous work and I know what you mean. > My original thoughts was based on telling writef that I want print a > null-terminated string rather than address. to!string will surely > work, but it implies double iteration, one in to!string to calculate > length (seeking for 0 char) and one in writef (printing). With long > strings this is suboptimal. What about something like this: > > struct CString(T) > if (isSomeChar!T) > { > T* str; > } > > @property > auto cstring(S : T*, T)(S str) > if (isSomeChar!T) > { > return CString!T(str); > } > > string test = "abc"; > immutable(char)* p = test.ptr; > > writefln("%s", p.cstring); // prints "abc" > > Here the char pointer type is "annotated" as null terminated string > and writefln can use this information. If CString implemented a toString method (probably the variant taking a sink delegate), this would already work. I'm not sure about performance though: Isn't writing out bigger buffers a lot faster than writing single chars? You could print every char individually, but wouldn't a p[0 .. strlen(p)] usually be faster?