Can I return a struct by initiating it into a Return in ANSI C?

Asked

Viewed 121 times

3

Good morning guys, I wonder 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 wouldn’t be the right way, but there is some way to do it or I have to create a temporary variable in the function to receive the values and then return it?

2 answers

2

Copia (with my translation) da Ouah’s answer on Stack Overflow in English.

You can do it using one literal compound (composite literal):

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

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

0

@pmg has 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};
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.