c++ - 从本地范围返回值?

标签 c++ c

在我们的代码库中遇到了这样的代码......这让我很担心。

int foo(int a); // Forward declaration.

int baz() {
    int result = {
         int a = dosomestuff();
         foo(a);
    } ? 0 : -1;
    return result;
}
  1. 这段代码的行为是否定义明确?
  2. 根据 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/

相关文章:

c++ - 寻找最近的较小素数的快速算法

c - 当不在 main 内部工作时

无法使用字符串变量中的指令执行内联汇编程序

C函数查找彼此不同的行

c++ - 有人可以帮助发现我的低锁定列表中的错误吗?

c++ - NodeJS native 模块 - 如何删除调试符号

c# - 通过示例规划编程项目(C# 或 C++)

c++ - std::vector 的 std::vector 邻接

c - 哪个标准定义了 "sysconf()"选项的值,例如 "_SC_MONOTONIC_CLOCK"?

c - 将多个单独的字符串传递给函数