从局部范围的返回值? [英] Return value from local scope?

查看:168
本文介绍了从局部范围的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

碰到一些code这样的在我们的code基...这让我很担心。

  INT美孚(INT一个); //向前声明。INT巴兹(){
    INT结果= {
         INT A = dosomestuff();
         富(一);
    }? 0:-1;
    返回结果;
}


  1. 这是$ C $的行为Ç明确定义?

  2. 它真正的工作,即结果变量被装入0或-1取决于的返回值美孚(一)


有关利息:code是不是这样写的最初 - 但是,它是什么,我想象这个无辜的前瞻性宏将铺开......

  INT美孚(INT一个); //向前声明。#定义BAR(){int类型的= dosomestuff();富(一); }INT巴兹(){
    INT结果= BAR()? 0:-1;
    返回结果;
}


解决方案

这是一个GCC扩展到C称为'语句前pressions:的 http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

最关键的事情是,声明前pression返回它的前pression价值的最后一件事:


  

在复合语句的最后一件事应该是一个前pression跟一个分号;此SUBEX pression的值作为整个构建体的值


在你的榜样,那会是什么美孚(一)的回报。

不过该块必须用括号为GCC接受的语法。

  INT富(); //向前声明。INT巴兹(){
    INT结果=({
         INT A = dosomestuff();
         富(一);
    })? 0:-1;
    返回结果;
}

我不知道该支持任何其他编译器。

Bumped into some code like this in our code base... which made me worried.

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

int baz() {
    int result = {
         int a = dosomestuff();
         foo(a);
    } ? 0 : -1;
    return result;
}

  1. Is the behavior of this code well-defined?
  2. Will it really work, that result variable gets loaded with 0 or -1 depending on the return value of foo(a)?


For interest: The code was not written like that originally - however, it is what I imagine this innocent-looking macro will roll out to...

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

#define BAR()  { int a = dosomestuff(); foo(a); }

int baz() {
    int result = BAR() ? 0 : -1;
    return result;
}

解决方案

This is a GCC extension to C called 'statement expressions': http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

The key thing is that a statement expression returns the last thing it does as the value of the expression:

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.

In your example, that would be whatever foo(a) returns.

However the block must be enclosed in parens for GCC to accept the syntax.

int foo(); // Forward declaration.

int baz() {
    int result = ({
         int a = dosomestuff();
         foo(a);
    }) ? 0 : -1;
    return result;
}

I'm unaware of any other compiler that supports this.

这篇关于从局部范围的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆