Is there a downside to declaring variables with auto in C++?

后端 未结 14 2057
-上瘾入骨i
-上瘾入骨i 2020-12-12 18:14

It seems that auto was a fairly significant feature to be added in C++11 that seems to follow a lot of the newer languages. As with a language like Python, I ha

14条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 18:45

    I'm surprised nobody has mentioned this, but suppose you are calculating the factorial of something:

    #include 
    using namespace std;
    
    int main() {
        auto n = 40;
        auto factorial = 1;
    
        for(int i = 1; i <=n; ++i)
        {
            factorial *= i;
        }
    
        cout << "Factorial of " << n << " = " << factorial <

    This code will output this:

    Factorial of 40 = 0
    Size of factorial: 4
    

    That was definetly not the expected result. That happened because auto deduced the type of the variable factorial as int because it was assigned to 1.

提交回复
热议问题