C++ Notes to Self: The auto Keyword

C/C++
‘The auto keyword directs the compiler to use the initialization expression of a declared variable, or lambda expression parameter, to deduce its type.’ [learn.microsoft.com]
Author

Dennis Chua

Published

February 15, 2017


In C++ auto type references is indicated by the auto keyword. Within a function block, it is used to declare a variable with automatic storage. Post C++11, auto keyword has changed. Now we use it in type declaration, leaving it up to the compiler to infer the type of the declared variable from the initialization statement, which is mandatory.

We can mix variables of related types in the initializer. The type of the auto variable will be of the variable with the widest storage requirement. (See the code below.)

The advantages of auto type references comes into light with C++ templates and lambda expressions.

#include <iostream>
int fsum(int a, int b);

using namespace std;

int main(int argc, char **argv) {
    auto i = 10;
    auto j {23.25};
    auto sum = i + 12;
    cout << "sum: " << sum << "\t" << "j: " << j << endl;
    auto k = i + j;
    cout << "k: " << k << endl;
    auto l = fsum(i, 334);
    cout << "l: " << l << endl;

    return 0;
}

int fsum(int a, int b) {
    return a + b;
}