正如 StoryTeller 所评论的,它是 C 模式下的 GCC 扩展。它在 C++ 中不起作用
在 GNU C 中,但不是 GNU C++ 中,您还可以将变量的类型声明为__auto_type
。在这种情况下,声明必须只声明一个变量,其声明符必须只是一个标识符,声明必须被初始化,并且变量的类型由初始化器确定;直到初始化程序之后,变量的名称才处于范围内。 (在 C++ 中,您应该使用 C++11 auto 来实现此目的。)__auto_type
,上面的“最大”宏可以写成:
#define max(a,b) \
({ __auto_type _a = (a); \
__auto_type _b = (b); \
_a > _b ? _a : _b; })
https://gcc.gnu.org/onlinedocs/gcc/Typeof.html https://gcc.gnu.org/onlinedocs/gcc/Typeof.html
正如你所看到的,它是not完全一样auto
在 C++ 中因为
- 它只能用于声明单个变量,而
auto
在C++中可以用来声明多个变量,例如auto i = 0, *p = &i;
- 它不能出现在函数(或 lambda)的返回类型或参数中,例如
auto f();
or void f(auto);
也无法替代auto
的情况下decltype(auto)
,或者像这样使用const auto& i = expr;
因为C中没有这样的功能
然而后来 Clang 采用了这个关键字并且C++ 也支持它在哪里完全一样auto
它甚至可以用于 C++98
此实现与 GCC 的不同之处在于还支持__auto_type
在 C++ 中,
将其视为相同auto
。我看不出有什么好的理由不这样做,因为
否则,打算从两种语言使用的标头都无法使用它(您
可以使用扩展为的定义__auto_type
or auto
取决于
语言,但 C++ pre-11 已损坏)。
添加对 GCC '__auto_type' 扩展的支持。 https://reviews.llvm.org/D12686
Clang++ 演示 https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:1,endLineNumber:13,positionColumn:1,positionLineNumber:13,selectionStartColumn:1,selectionStartLineNumber:13,startColumn:1,startLineNumber:13),source:%27%23include+%3Ciostream%3E%0Aint+main()%0A%7B%0A++++__auto_type++x+%3D+4%3B%0A++++__auto_type++y+%3D+3.37%3B%0A++++__auto_type++ptr+%3D+%26x%3B%0A++++std::cout+%3C%3C+typeid(x).name()+%3C%3C+!%27%5Cn!%27%0A++++++++++++++%3C%3C+typeid(y).name()+%3C%3C+!%27%5Cn!%27%0A++++++++++++++%3C%3C+typeid(ptr).name()+%3C%3C+!%27%5Cn!%27%3B%0A+%0A++++return+0%3B%0A%7D%0A%27),l:%275%27,n:%270%27,o:%27C%2B%2B+source+%231%27,t:%270%27)),k:46.581196581196586,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:clang1100,filters:(b:%270%27,binary:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%270%27,intel:%270%27,libraryCode:%271%27,trim:%271%27),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:%27-O1%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:%275%27,n:%270%27,o:%27x86-64+clang+11.0.0+(Editor+%231,+Compiler+%231)+C%2B%2B%27,t:%270%27)),k:53.41880341880342,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,m:100,n:%270%27,o:%27%27,t:%270%27)),version:4
它还支持目标C https://twitter.com/armadsen/status/742812778512015361