在我们的代码库中遇到了这样的代码......这让我很担心。
int foo(int a); // Forward declaration.
int baz() {
int result = {
int a = dosomestuff();
foo(a);
} ? 0 : -1;
return result;
}
- 这段代码的行为是否定义明确?
- 根据
foo(a)
的返回值,result
变量加载 0 或 -1 真的有用吗?
感兴趣的是:代码最初并不是这样写的 - 然而,我认为这个看似无辜的宏将推出......
int foo(int a); // Forward declaration.
#define BAR() { int a = dosomestuff(); foo(a); }
int baz() {
int result = BAR() ? 0 : -1;
return result;
}
最佳答案
这是 GCC 对 C 的扩展,称为“语句表达式”:http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
关键是语句表达式返回它做的最后一件事作为表达式的值:
The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct.
在您的示例中,这将是 foo(a)
返回的任何内容。
但是,为了让 GCC 接受语法,该 block 必须包含在括号中。
int foo(); // Forward declaration.
int baz() {
int result = ({
int a = dosomestuff();
foo(a);
}) ? 0 : -1;
return result;
}
我不知道有任何其他支持此功能的编译器。
关于c++ - 从本地范围返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4391033/