【问题标题】:Can I return a initialized struct on one line in ANSI C?我可以在 ANSI C 中的一行上返回一个初始化的结构吗?
【发布时间】:2014-10-31 06:55:08
【问题描述】:

我只是想知道我是否可以做这样的事情......

typedef struct Result{
  int low, high, sum;
} Result;

Result test(){
  return {.low = 0, .high = 100, .sum = 150};
}

我知道这是错误的方法,但我可以这样做还是我需要创建一个局部变量来接收值然后返回它?

【问题讨论】:

    标签: c struct initialization return ansi


    【解决方案1】:
    struct Result
    {
        int low;
        int high;
        int sum;
    };
    
    then to create an instance of the struct
    
    struct Result myResult;
    
    Regarding your question...
    
    prototype for the test function
    
    void test( struct Result *myResult );
    
    invoke the function by:
    
    test( &myResult );
    
    the test function:
    
    void test( struct Result *argResult )
    {
        argResult->low  = 0;
        argResult->high = 100;
        argResult->sum  = 150;
    }
    

    【讨论】:

    • Typedef'ing 结构被贬值了???另外,test( struct Result &myResult ) - 这从什么时候开始成为 C 语言中“调用函数”的一种方式?
    • 你对,我改行调用函数
    • 我找不到对被贬值的结构的 typedef 的原始引用,所以我删除了该语句
    【解决方案2】:

    您可以使用 复合文字

    Result test(void)
    {
        return (Result) {.low = 0, .high = 100, .sum = 150};
    }
    

    (){} 是复合字面量运算符,复合字面量是 c99 中引入的一个特性。

    【讨论】:

    • 此方法导致编译器分配 ram 以保存“结果”结构,字段最初复制到该结构,然后再次复制到调用方的“结果”结构实例.这两个副本和 Result 结构的分配是真正的 RAM 和 CPU 周期浪费。
    • @user3629249:但这些可以优化并且是特定于 ABI 的。在 Linux/x86-64 上,两个字段 struct 通常在两个寄存器中返回。
    • @user3629249:优化编译器将尽可能将结构放入单个寄存器中(在 x64 上,whatever fits into 8 bytes 被写入单个寄存器),当然optimize the entire result completely if possible
    • 如果使用简单的结构,你可以避免写字段名:return (Result){0, 100, 150};.
    • 那么,由于括号,这在技术上是一种类型转换吗?顺便说一句,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多