Search code examples
c++c++11c++14autostorage-class-specifier

Confusion about auto keyword in C++


I'm confused by the following piece of code:

#include <iostream>
using namespace std;

int *foo()
{
   //Operation
}

int main ()
{
        auto int ret = foo();
}

I compiled the above code under GCC, but I got the following error:

error: two or more data types in declaration of 'ret'
         auto int ret = foo();

But, if I remove int type, like so:

auto ret = foo();

then it runs successfully.

auto is a storage class and int is a data type, then why do I get the error "two or more data types" in the first case?


Solution

  • auto is not a storage class. It used to be, before C++11. But it was completely useless, so the keyword was re-purposed to allow automatic type inference. So when you say:

    auto int ret = foo();
    

    You are basically declaring the object to have 2 types (or possibly the same type twice), and that is an error. And when you say:

    auto ret = foo();
    

    The type of ret is determined by whatever the function foo returns, which is int* in this case.