auto keyword was introduced with C++11. It reduces the amount of code you have to write, reduces repetitive code and the number of required changes. Sadly, many C++ developers are not aware of how useful this keyword is. Especially embedded code can gain a lot by its usage.
In this article, I try to explain a number of useful cases of the
auto keyword, using Arduino example code. The same principles are valid for any embedded environment which is using a modern C++ compiler. The C++11 standard is eight years old, and meanwhile, every C++ compiler should support it.
The examples are written for Arduino or Adafruit SAMD boards using the Arduino IDE. The toolchain for these boards use a compiler which supports more features explained in this article. Using
auto with AVR code is possible too, just give it a try.
The “auto” Keyword
auto keyword was introduced to instruct the compiler to automatically deduce a type from the given context. In programming language terms, they call this a placeholder type specifier.
C++11 mainly introduced the
auto keyword for variable declarations. These are the main focus of this article.
Simple Variable Declarations
At any point in your code, where you declare a variable which is initialized, you can use
auto instead of a type.
auto variable = <some expression>Continue reading Write Less Code using the “auto” Keyword