Reputation: 156
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.
Upvotes: 4
Views: 5926
Reputation: 41932
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; })
As you can see, it's not exactly the same as auto
in C++ because
auto
in C++ can be used to declare multiple variables like auto i = 0, *p = &i;
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 asauto
. 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
orauto
depending on the language, but then C++ pre-11 is broken).
It's also supported in Objective C
Upvotes: 4