printf, writeln, writefln

Ali Çehreli acehreli at yahoo.com
Wed Dec 7 16:18:33 UTC 2022


On 12/6/22 15:07, johannes wrote:

 > 'write' prints out the address
 > of the first byte. This is odd to me because printf does the job
 > correctly.

printf behaves as what you expect because %s means dereferencing the 
pointer values and printing the char contents until printf sees '\0'.

 > But I think to understand that write in D interpretes char*
 > as a pointer to a byte.

Because it is. :) char* is nothing but a pointer to char. ('byte' exists 
as well, so I user 'char'.)

 > it seems the
 > formatting "%s" has another meaning in D ?

Yes. %s means the string representation of the variable. Sring 
representation of a pointer happens to be the hexadecimal representation 
of its value.

User-defined types can define a toSring() member function to decide how 
their string representation should be.

%s is the default: write(x) or writeln(x) would print like %s would.

This all works because these functions are templates, taking advantage 
of type deduction: They know the exact type of what they are printing. 
So, %s is known for that type.

printf that came from C is not templatized, so the programmer has to 
tell it what to do like with %s.

Ali



More information about the Digitalmars-d-learn mailing list