What is the correct use of auto?

Unknown W. Brackets unknown at simplemachines.org
Fri Apr 11 13:58:48 PDT 2008


It might help you to understand auto if you try this:

auto i;

It will not compile.  In this case, i has no type.  Remember that i is 
not some boxed variable or something... it's simply type inference.

-[Unknown]


Hans W. Uhlig wrote:
> Unknown W. Brackets wrote:
>> A great example is when using a library.  Instead of using a "void*" 
>> or something like that, you'd use an auto.
>>
>> Example:
>>
>> auto valueType = library.getSomething();
> 
> I am coming from C and Java (sorry no C++), why wouldn't you declare a 
> typed variable to store the class. Doesn't using auto introduce 
> ambiguity to the compiler and the code itself.
> 
> And this is secondary but how would you use any form of autosense 
> against this since its type can change from execution to execution.
> 
>>
>> auto souffle = library.makeSomethingSouffle(valueType);
>> library.somethingElse(souffle);
>>
> 
> Again what is a souffle and why wouldnt you want it to be
> Souffle mySouffle = library.makeSomethingSouffle(valueType); so that its 
> properties are known at compile time.
> 
>> Another use is when a particular section of your code doesn't care 
>> about the type, and you're just paper-pushing.  This way, even if you 
>> need to change the type later, you don't have to revisit the code 
>> (just recompile it.)
> 
> why bother to paper push if the value is unnecessary. Why not simply 
> discard and move on?
> 
>>
>> It's also handy for this:
>>
>> auto abc = new com.example.somethinglong.modulename.Package();
>>
>> Although mostly you would use an alias for that anyway.
>>
>> And that's not even mentioning templates, where it's very very useful.
>>
>> -[Unknown]
>>
>>
>> Hans W. Uhlig wrote:
>>> I have been reading through the specification and playing with D more 
>>> and more, what is the purpose of auto. I can understand in languages 
>>> with scalar types handling datatypes on assignment but on a strictly 
>>> typed language like C or D when would auto(as a variable declaration) 
>>> provide more useful functionality then it removes from readability.
>>>
>>> When would this be useful rather then simply specifying the type?



More information about the Digitalmars-d mailing list