24

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?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
João Esteves
  • 341
  • 2
  • 3

2 Answers2

40

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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • This method results in ram being allocated, by the compiler, to hold a 'Result' struct, where the fields are initially copied to, then copied again to the callers' instance of the 'Result' struct. Those two copies and the allocation of the Result struct are real RAM and CPU cycle wasters. – user3629249 Sep 07 '14 at 14:19
  • 2
    @user3629249: But these can be optimized and are ABI specific. On Linux/x86-64 a two-fields `struct` is often returned in two registers. – Basile Starynkevitch Sep 07 '14 at 14:40
  • @user3629249: an optimizing compiler will fit the struct into a single register whenever possible (on x64, [whatever fits into 8 bytes](https://godbolt.org/z/SDW76d) gets written to a single register), and of course will [optimize the entire result completely if possible](https://godbolt.org/z/QWk7gz). – vgru Apr 18 '19 at 13:13
  • 1
    If using simple structs, you can avoid writing the fields' names: `return (Result){0, 100, 150};`. – tleb Aug 05 '20 at 14:38
  • So, is this technically a type cast, because of the parentheses? And by the way, THANK YOU SO MUCH. – Palbitt Apr 21 '21 at 02:19
-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;
}
user3629249
  • 16,402
  • 1
  • 16
  • 17