Auto type specifier

Not JUCE related, but the first time I came across it is in the JUCE framework and I know Jules etc. are big on doing things the proper way, so curious to know the musings/advice from the JUCErs here.

I’m really incompetent at programming, in fact, mid way through crunching Bruce Eckel’s ‘Thinking in C++’ I decided to go through another book (Teach yourself C++ in one hour a day) before I could even finish the first volume of Thinking. This is how amateur I am.

Anyway, for dumb dumbs like me, the auto type specifier seems to be more pain than it’s worth, unless I’m missing something? I like knowing easily what type something is, so what is the benefit to using it, and why is it used so often in JUCE?

Many thanks.

Consider this code:

AudioBuffer<float> buffer = AudioBuffer<float>(1, 1024);
auto buffer = AudioBuffer<float>(1, 1024);

Both do the same thing, but which line is more readable and takes less typing?
Therein lies an answer :slight_smile:

1 Like

Another argument, your code might not even mention the type:

auto value = getFoo();

If I later refactor getFoo to return double instead of float, my code still does the expected thing, just in a higher precision.
What you should care about, when you use auto, is to add const if applicable and * (it’s a pointer) or & (it’s a reference, not take the address of).

So generally auto is a case of DRY and avoiding unnecessary implicit casts.

1 Like

auto also has the advantage that it’s impossible to leave it uninitialised.

int x;              // maybe 0 depending on context, but probably indeterminate
auto x = 0;         // definitely 0
auto x = int { 0 }; // definitely 0 and obviously an int

Great points. Thanks all very much.

If you want to go deeper, Herb Sutter’s blog (and books – his ‘Exceptional C++’ books are aging but still critical reading) is always a first-call resource. On his ‘almost always auto’ recommendation: