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?
Oh, yeah, one more missing piece: returning a struct from a function does a move and not a copy.
Structure members can be initialized using curly braces '{}'.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
Generally, the initialization of the structure variable is done after the structure declaration. Just after structure declaration put the braces (i.e. {}) and inside it an equal sign (=) followed by the values must be in the order of members specified also each value must be separated by commas.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With