Search code examples
c++auto

Type inferred by C++ auto


How does C++'s auto infer data types in case of for loops - from initialization, or from condition?

long long n;
cin>>n;
for(auto i=1; i<=n; i++)
    cout << ((i * i) * ((i * i) - 1)) / 2 - 2 * (2 * (i - 1) * (i - 2)) << "\n";

Here, will i be an integer of long long? My code failed (probably due to overflow - negative values in output, n = 10000) when I used auto and passed when I used long long.


Solution

  • For the simpler statement

    auto i = 1;
    

    it's obvious that i is an int type, since 1 is a literal of type int. That carries over to the declaration inside the for loop. C++ is remarkably self-consistent.

    The type of the stopping conditional i <= n is a bool so that wouldn't be much use to you.

    If you want the index type to be the same as n, then use

    for (decltype(n) i = 1;
    

    at the start of the loop.