Home > front end >  accessing a value in return struct
accessing a value in return struct

Time:10-28

if you have a function that returns a struct, is it then possible to access on of the internal values in struct that is returned, without having to handling the whole struct.

The code could look something like this;

struct myStruct
{
    int value1;
    int value2;
};

myStruct functionReturningStruct(void);

....


value2 = functionReturningStruct().value2

if it's possible in anyway, how?

CodePudding user response:

Why don't you test?

#include <stdio.h>

struct myStruct
{
    int value1;
    int value2;
};

struct myStruct functionReturningStruct(void)
{
    return (struct myStruct){10, 20};
}

int main(void)
{
    int value = functionReturningStruct().value2;

    printf("%d", value);
    return 0;
}

CodePudding user response:

It's possible.

Implementations I found use an implicit first argument of functionReturningStruct() which points to the structure, that is temporary allocated by the compiler on call point.

Indeed, it is equivalent to

{
    struct myStruct __temp_myStruct;

    __actual_functionReturningStruct(&__temp_myStruct);

    value2 = __temp_myStruct.value2;
}
  • Related