auto init & what the code means

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Dec 27 09:06:55 PST 2010


On 12/26/10 6:04 PM, Tomek Sowiński wrote:
> spir<denis.spir at gmail.com>  wrote:
>> On Sun, 26 Dec 2010 14:54:12 +0100
>> Andrej Mitrovic<andrej.mitrovich at gmail.com>  wrote:
>>
>>> int i;    // auto-initialized to int.init
>>> int i = void; // not initialized
>>
>> Thanks. Actually this solves my "semantic" issue, did not even think
>> at 'void'. (I will use it often). By the way, I don't want to play the
>> superhero with uninitialised values, simply sometimes the initial
>> value cannot be known at declare place.
>> 	int i;
>> 	if (foo)
>> 	   i=0;
>> 	else if (bar)
>> 	   i=1;
>> 	else
>> 	   i=2;
>> 	playWith(i);
>
> int i = foo ? 0 : bar ? 1 : 2;

The idiom breaks when you need e.g. a loop, which can't be an 
expression. Fortunately you can always use a lambda - a common idiom in 
functional code:

int i = { code code code }();

This is all the more necessary and interesting with immutability - you 
must initialize an immutable value only once.

immutable int i = { code code code }();


Andrei


More information about the Digitalmars-d mailing list