auto init & what the code means

spir denis.spir at gmail.com
Mon Dec 27 04:28:29 PST 2010


On Sun, 26 Dec 2010 14:04:28 -0800
Jonathan M Davis <jmdavisProg at gmx.com> wrote:

> On Sunday 26 December 2010 07:08:22 Andrei Alexandrescu wrote:
> > On 12/26/10 8:54 AM, spir 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);
> > 
> > Problem with = void for elaborate types is that you need to use
> > emplace(&var, expr) to initialize them later.
> 
> And of course the _big_  problem with = void is that you're dealing with garbage 
> if you don't actually initialize the variable before you use it. It's a good 
> addition for performance-critical code, but in general, it's a _bad_ idea to 
> use. It solves a major problem which exists in C and C++ with regards to 
> undefined and undeterministic behavior. I'd get very worried if I started seeing 
> code that used it all over the place. There are straightforward cases where it's 
> obvious that it's of benefit and obvious that the variable in question is being 
> initialized, but beyond that, it really shouldn't be used.
> 
> - Jonathan M Davis

Right, regarding Andrei's note about void and yours, I think it's better to use a plain, but *conventional*, comment. I guess
	int i=0;
versus
	int i;		// undef
do the job. The point here (of my initial post) is correct documentation of code meaning for the reader's benefit; not changing actual process under the hood. But such practices need adoption by a large (or leading) proportion of the language's community. Which may be hard because code clarity has never been, AFAIK, a primary concern in C-line language uses.

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

spir.wikidot.com



More information about the Digitalmars-d mailing list