Is there a downside to declaring variables with auto in C++?

DxAlpha picture DxAlpha · Jan 13, 2016 · Viewed 13.6k times · Source

It seems that auto was a fairly significant feature to be added in C++11 that seems to follow a lot of the newer languages. As with a language like Python, I have not seen any explicit variable declaration (I am not sure if it is possible using Python standards).

Is there a drawback to using auto to declare variables instead of explicitly declaring them?

Answer

Peter picture Peter · Jan 13, 2016

You've only asked about drawbacks, so I'm highlighting some of those. When used well, auto has several advantages as well. The drawbacks result from ease of abuse, and from increased potential for code to behave in unintended ways.

The main drawback is that, by using auto, you don't necessarily know the type of object being created. There are also occasions where the programmer might expect the compiler to deduce one type, but the compiler adamantly deduces another.

Given a declaration like

auto result = CallSomeFunction(x,y,z);

you don't necessarily have knowledge of what type result is. It might be an int. It might be a pointer. It might be something else. All of those support different operations. You can also dramatically change the code by a minor change like

auto result = CallSomeFunction(a,y,z);

because, depending on what overloads exist for CallSomeFunction() the type of result might be completely different - and subsequent code may therefore behave completely differently than intended. You might suddenly trigger error messages in later code(e.g. subsequently trying to dereference an int, trying to change something which is now const). The more sinister change is where your change sails past the compiler, but subsequent code behaves in different and unknown - possibly buggy - ways.

Not having explicit knowledge of the type of some variables therefore makes it harder to rigorously justify a claim that the code works as intended. This means more effort to justify claims of "fit for purpose" in high-criticality (e.g. safety-critical or mission-critical) domains.

The other, more common drawback, is the temptation for a programmer to use auto as a blunt instrument to force code to compile, rather than thinking about what the code is doing, and working to get it right.