The auto Specifier C++

The auto specifier deduces the type of a declared variable from its initialization expression.
This means that a variable can assume the proper type based on the value it is initialized with.

#include <iostream>
using namespace std;

int main() {
    auto d = 1.5;
    auto i = 2 + 2;
    
    cout << d + i;
    
    return 0;
}

In the code above, the compiler automatically uses double for the variable d and int for the variable i.
This only works if you initialize the variable, as without initialization the compiler cannot “guess” the type to use.

The auto specifier can be used for function return types as well.
For example:

#include <iostream>
 namespace std;

auto add(int x, int y) {
    return x + y;
}
int main() {
    auto sum = add(5, 6);
    cout << sum;

    return 0;
}

The auto specifier cannot be used with function parameters, because the compiler can’t infer types for function parameters at compile time.

The auto specifier is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.