Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 692
João Esteves Avatar asked Sep 06 '14 13:09

João Esteves


People also ask

Does returning a struct copy it?

Oh, yeah, one more missing piece: returning a struct from a function does a move and not a copy.

How are structs initialized in C?

Structure members can be initialized using curly braces '{}'.

How does one initialize a structure?

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 ( = ).

How do you initialize a struct variable?

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.


1 Answers

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.

like image 58
ouah Avatar answered Oct 14 '22 01:10

ouah