Search code examples
c++ckeywordtype-inferenceauto

Is there any difference between auto and __auto_type?


I've been using __auto_type in C for sometime now and I was wondering if it's any different from auto in C++. Are they implemented differently?

I've tried searching for this, but it doesn't yield any results, since searching for __auto_type in C returns articles about auto in C++. It feels like a forgotten keyword.


Solution

  • As StoryTeller commented, it's a GCC extension in C mode. It doesn't work in C++

    In GNU C, but not GNU C++, you may also declare the type of a variable as __auto_type. In that case, the declaration must declare only one variable, whose declarator must just be an identifier, the declaration must be initialized, and the type of the variable is determined by the initializer; the name of the variable is not in scope until after the initializer. (In C++, you should use C++11 auto for this purpose.) Using __auto_type, the “maximum” macro above could be written as:

       #define max(a,b) \
         ({ __auto_type _a = (a); \
         __auto_type _b = (b); \
         _a > _b ? _a : _b; })
    

    https://gcc.gnu.org/onlinedocs/gcc/Typeof.html

    As you can see, it's not exactly the same as auto in C++ because

    • it can only be used to declare a single variable, while auto in C++ can be used to declare multiple variables like auto i = 0, *p = &i;
    • it can't appear in the return type or arguments of a function (or lambda) like auto f(); or void f(auto);

    It can't also replace auto in case of decltype(auto), or be used like const auto& i = expr; because there are no such features in C

    However later Clang adopted this keyword and also supports it in C++ where it's exactly the same as auto and it can even be used for C++98

    This implementation differs from GCC's in also supporting __auto_type in C++, treating it the same as auto. I don't see any good reason not to, because otherwise headers intended to be used from both languages can't use it (you could use a define that expands to __auto_type or auto depending on the language, but then C++ pre-11 is broken).

    Add support for GCC's '__auto_type' extension.

    Demo for Clang++

    It's also supported in Objective C