literal notation considered harmful (was: Re: Slides from my ACCU Silicon Valley talk)

spir denis.spir at gmail.com
Tue Dec 14 02:43:38 PST 2010


On Tue, 14 Dec 2010 05:15:05 -0500
bearophile <bearophileHUGS at lycos.com> wrote:

> > Magic constants have issues - be they strings, integrals, or doubles. I 
> > have trouble thinking that complex literals are somehow exempt.  
> 
> I partially agree. They need to be used with care (and defined only once in the code). On the other hand removing all integral literals from my D programs isn't going to improve them :-)

What about (char &) string literals? Hello, World! in D:

void main () {
    string message = [
        0x48,
        0x65,
        0x6c,
        0x6c,
        0x6f,
        0x2c,
        0x20,
        0x57,
        0x6f,
        0x72,
        0x6c,
        0x64,
        0x21,
    ];
    writeln(message);
}

And be happy that int's auto-cast to char's! Else, it would be:

void main () {
    string message = [
        cast(char)0x48,
        cast(char)0x65,
        cast(char)0x6c,
        cast(char)0x6c,
        cast(char)0x6f,
        cast(char)0x2c,
        cast(char)0x20,
        cast(char)0x57,
        cast(char)0x6f,
        cast(char)0x72,
        cast(char)0x6c,
        cast(char)0x64,
        cast(char)0x21,
    ];
    writeln(message);
}

(works!)
(Should we put this version on Wikipedia's Hello, World! page http://en.wikipedia.org/wiki/Hello_world_program_examples ?)


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list