I just wanna know if I can do something like that...
我只想知道我是否可以做那样的事......
typedef struct Result{
int low, high, sum;
} Result;
Result test(){
return {.low = 0, .high = 100, .sum = 150};
}
I know that is the wrong way, but can I do that or I need to create a local variable to receive the values and then return it?
我知道这是错误的方式,但我可以这样做,还是我需要创建一个局部变量来接收值然后返回它?
2 个解决方案
#1
19
You can do so by using a compound literal:
您可以使用复合文字来执行此操作:
Result test(void)
{
return (Result) {.low = 0, .high = 100, .sum = 150};
}
(){}
is the compound literal operator and compound literal is a feature introduced in c99.
(){}是复合文字运算符,复合文字是c99中引入的一个特性。
#2
-5
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;
}
#1
19
You can do so by using a compound literal:
您可以使用复合文字来执行此操作:
Result test(void)
{
return (Result) {.low = 0, .high = 100, .sum = 150};
}
(){}
is the compound literal operator and compound literal is a feature introduced in c99.
(){}是复合文字运算符,复合文字是c99中引入的一个特性。
#2
-5
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;
}