繁体   English   中英

我可以在ANSI C中的一行上返回初始化结构吗?

[英]Can I return a initialized struct on one line in ANSI C?

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

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

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

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

您可以使用复合文字来完成此操作

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

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

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM