Why does a variable need to be declared as auto?

Debojit Acharjee 455 Reputation points
2023-06-12T11:21:12.8333333+00:00

The "auto" keyword is used to make a variable automatic, but even without using the keyword, a variable becomes automatic by default. In the following program, the variable inside two blocks of statements is automatic and works the same way.

#include <stdio.h>

int main()
{
    int a = 1;

    printf("Value of 'a' is %d\n", a);

    {
        auto int a = 2;
        printf("Value of 'a' is %d\n", a);
    }

    printf("Value of 'a' is %d\n", a);

    {
        int a = 3;
        printf("Value of 'a' is %d\n", a);
    }

    printf("Value of 'a' is %d", a);

    return 0;
}

Output:

Value of 'a' is 1

Value of 'a' is 2

Value of 'a' is 1

Value of 'a' is 3

Value of 'a' is 1

Developer technologies C++
{count} votes

2 answers

Sort by: Most helpful
  1. David Lowndes 2,640 Reputation points MVP
    2023-06-12T11:29:16.27+00:00

    The auto keyword is now used to let the compiler deduce what the type should be.

    What compiler are you using that lets you compile:

    auto int a = 2;

    ?

    I receive these errors:

    E0084 invalid combination of type specifiers

    C3530 'auto' cannot be combined with any other type-specifier

    1 person found this answer helpful.
    0 comments No comments

  2. Sreeju Nair 12,661 Reputation points
    2023-06-12T11:35:22.23+00:00

    In C++, the auto keyword lets you define a variable with the type based on its initialization expression. something similar to var keyword in C#, though auto has much higher scope.

    See the program you mentioned modified with to see the correct usage of auto.

    #include <stdio.h>
    
    int main()
    {
        int a = 1;
    
        printf("Value of 'a' is %d\n", a);
    
        {
    //correct declaration of auto variable. 
            auto a = 2;
            printf("Value of 'a' is %d\n", a);
        }
    
        printf("Value of 'a' is %d\n", a);
    
        {
            int a = 3;
            printf("Value of 'a' is %d\n", a);
        }
    
        printf("Value of 'a' is %d", a);
    
        return 0;
    }
    

    The auto can be used even as a function return type. see the following example.

    #include <iostream>
    // Create a function
    auto myFunction() {
      return 3 * 2;
    }
    
    int main() {
      printf("Value of 'a' is %d", myFunction());
      return 0;
    }
    
    

    I recommend you to refer the following article for further details.

    https://learn.microsoft.com/en-us/cpp/cpp/auto-cpp?view=msvc-170

    Hope this helps

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.