Can I return a struct by initializing it inside a return in ANSI C?

3

Good morning, I'd like to know if I can do something like this ...

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

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

I know this would not be a right way, but is there any way to do this or do I have to create a temporary variable in the function to get the values and then return it?

    
asked by anonymous 06.09.2014 / 15:36

2 answers

2

Copy (with my translation) from Ouah's answer to Stack Overflow .

You can do this using a compound literal (literal compound):

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

(){} is the operator for compound literal that was introduced with version C99.

    
06.09.2014 / 15:43
0

@pmg said it all (+1); Just one more variant:

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

Result teste(){
  return (Result){0,100,150};
}

int main(){
  printf("%d\n",teste().sum);
  return 0;
}

or without typedef:

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

Result teste(){  
  return (struct Result){0,100,150};
}
    
13.11.2015 / 13:49