我刚刚读了这样的代码:
auto value = ({
auto it = container.find(key);
it != container.end() ? it->second : default_value;
});
Run Code Online (Sandbox Code Playgroud)
这个叫什么({})?我想我以前从未见过这个。
#include <stdio.h>
int main()
{
int sum = 0, result = (({for (int i = 0; i < 5; i++) sum += i;}), sum);
printf("result = %d\n", result);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
显示
result = 10
Run Code Online (Sandbox Code Playgroud)
我正在使用 gcc 中 C 的默认版本。它特定于 gcc 吗?我知道(a, b)回报b,但我没想到它会在阻塞时发挥a作用{}。谁能解释它为什么起作用以及为什么必须将块括起来才能使其起作用?
#define编辑:这是我正在尝试的一个人为的简化示例。一些程序员的评论(谢谢)澄清了这一点。案件结案。
我最近注意到GCC/Clang中有一个奇怪的有效C/C++表达式,这是我以前从未见过的。这是C++中的示例,但类似的表达式也适用于C:
int main(){
int z = 5;
auto x = ({z > 3 ? 3 : 2;}); // <-- expression
std::cout << x;
}
Run Code Online (Sandbox Code Playgroud)
它的作用在某种程度上是显而易见的,但我想知道它叫什么。由于它在MSVC中不值得,我猜它是一个非标准扩展。但是有什么东西也适用于MSVC吗?特别是在C?
我发现两个相似的语句之间有不同的执行顺序(唯一的区别是下面有一个额外的;)。析构函数顺序不同。C++ 是否有相应的规范,或者它只是一种未指定的行为?
环境:GCC10
#include <iostream>
template <int num>
struct S {
S() {std::cout << "S(" << num << ")\n"; }
~S() {std::cout << "~S(" << num << ")\n"; }
};
int main() {
({S<1>(), S<2>();});
std::cout << "-----------------------------------\n";
({S<3>(), S<4>();;});
}
Run Code Online (Sandbox Code Playgroud)
输出:
S(1)
S(2)
~S(1)
~S(2)
-----------------------------------
S(3)
S(4)
~S(4)
~S(3)
Run Code Online (Sandbox Code Playgroud) 我有两个使用相同技巧和功能的程序,只有其中一个可以编译。
A)这一个可以编译,并且可以按预期工作:
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/*
* int mallocs(T **restrict p, ptrdiff_t nmemb);
*/
#define mallocs(ptr, nmemb) ( \
{ \
ptrdiff_t nmemb_ = (nmemb); \
__auto_type ptr_ = (ptr); \
int err_; \
\
err_ = 0; \
if (ptr_ == NULL) { \
errno = EINVAL; \
err_ = EINVAL; \
goto ret_; \
} \
if (nmemb_ < 0) { \
*ptr_ = NULL; \
errno = EOVERFLOW; \
err_ …Run Code Online (Sandbox Code Playgroud)