Auto keyword
Okay, we have done a whole lot with variables, how to declare them, what values they can store, how to change those values, if of course the variable is non-constant, oh yes, constant variables, etc. We know, it’s a lot. Is that it? Not quite. As your journey through this notoriously tricky language goes, you will encounter a number of user-defined types ( these will be explained in later chapters), which in some cases get really complicated. Now, if someone defines a type which looks very complicated, do you really need to know the exact definition of the data type to use a variable of that type and store it somewhere in memory. The answer is actually no! Luckily, the good people who developed the C++ compiler have added a keyword which can be used as a type declaration and it’s name is quite intuitive – it’s auto! Auto keyword will detect the data type “automatically” from the expression on the right side of the “=“. Easy, right? You may have noticed one catch – when using auto, you must define your variable. It can’t just guess the type from thin air, it needs something to compare the data type to.
In the next example we will try to illustrate how this might be useful. Keep in mind that in the example a complicated variable definition is used, so the point here isn’t for you to understand it at this point, but just to see the advantages the auto keyword brings you.
int* (*monster_var[])(double*, char*) = __get_monster_array(_a, _b); /* Some TERRYFYING definition
of the variable "monster_var" */
auto a = monster_var; //THAT'S IT. "a" has the same type as "monster_var" and has the same value
auto x = 5; // Compiler will know that the variable is an integer
See? That wasn’t so hard. Just keep in mind not to overuse the auto keyword. It does bring some advantages, but it shouldn’t be overused where traditional variable declaration can be used.
Table of contents
- Loops, Pointers and Functions
- Classes and Objects
- Operator Overloading
- Class Inheritance
- Exceptions
- Namespaces
- Templates
- Standard Library
- Additional Problems