Aller au contenu

The auto Keyword

What is the auto Keyword

C++ is a strongly typed language and the type of each variable must be known at compile time. Before C++11, the programmer had to specify the type of each variable when declaring the variable. However, since C++11, when declaring a variable, the programmer does not need to state its type explicitly, when it can be deduced from its initializer. Some examples where auto can be used are shown below:

#include <iostream>

int main() {
    // Put your code here
    auto a = true; // b is a boolean
    std::cout << "a is " << a << " " << typeid(a).name() << std::endl;
    auto b = 's'; // ch is a char
    std::cout << "b is " << b << " " << typeid(b).name() << std::endl;
    auto c = 1234; // i is an int
    std::cout << "c is " << c << " " << typeid(c).name() << std::endl;
    auto d = 1234L; // l is a long
    std::cout << "d is " << d << " " << typeid(d).name() << std::endl;

}

When Should a Programmer Use auto

In general, auto should or could be used when there isn’t a specific reason to mention the type explicitly. Reasons for specifying the type explicitly are:

  • Readability: when the type of a variable or the type returned by a function must be clearly visible to users of the variable or function.
  • Precision: When the range of a variable must be made explicit, like between a float or double variable.

Advantages of Using auto

The use of auto provides the following advantages:

  • Avoids Redundancy: Eliminates unnecessary type repetition
  • Shorter Names: Avoids writing long type names, which is particularly true when using template classes.

When NOT to Use auto

Although using auto is helpful, it should not be an easy way out for programmers. Good programmers should understand how auto works and what types are inferred by the compiler. Use auto judiciously to maintain code clarity.

Restrictions for Using auto

  • auto can only be used when the type can be deduced from the initializer
  • Plain auto cannot be used with function declarations (return types must be explicit)
  • In some complex template code, the deduced type may not be what you expect