The auto keyword makes C++ to infer type based on the value initially assigned to it.
The literal assigned to the variable at initialization determines the type.
The compiler figures out a suitable data type. Here are some examples:
auto index = 3; auto multiple = 2.25F; auto rate = 500 / 3.0;
These statements create an index variable that holds an int value, a multiple variable that holds a float and a rate variable that holds a double.
In the preceding example is the same as follows:
int index = 3; float multiple = 2.25F; double rate = 500 / 3.0;
When using auto, you must assign the variable a value at initialization.
Multiple variables can be assigned with an auto keyword as long as every one of the variables has the same data type.
auto a = 86, b = 75, c = 309;
The following code shows how to use auto to define variables.
#include <iostream> int main() // w w w . ja va 2 s . c o m { // define character values auto strength = 80; auto accuracy = 45.5; auto dexterity = 24.0; // define constants const auto MAXIMUM = 50; // calculate character combat stats auto attack = strength * (accuracy / MAXIMUM); auto damage = strength * (dexterity / MAXIMUM); std::cout << "\nAttack rating: " << attack << "\n"; std::cout << "Damage rating: " << damage << "\n"; }