I have a function returning a union
type. Is it allowed by the standard (C99) to access a field of a returned value directly from the call without copying the value to a variable. Here an example to illustrate what I mean:
union thinga { int integ; char arr[4]; };
union thinga f(void)
{
union thinga t = {.integ = 1};
return t;
}
int main(void)
{
printf("thinga is %d\n", f().integ);
}
Is the call with field f().integ
allowed? In my example it's a union
but the issue is the same for struct
.
I ask the question, because I remember vividly that gcc 3.3 on Solaris didn't like this construct and would warn like hell. Its problem was that it had to generate internally an invisible variable to be able to access the field of the struct
or the union
. Newer compilers seem not to mind the construct but I would like to know if there is a hidden catch (i.e. undefined bevaviour
that I didn't think of.
EDIT: Ok it looks like my contrived example is a bit too simple and as commenter 2501 noticed by giving links to array decaying to pointer on out of scope objects, let's see if we are in the same situation if I change a bit my code.
union thinga f(const char *val)
{
union thinga t = {.integ = 0};
t.arr[0] = val[0];
return t;
}
int main(void)
{
printf(" thinga.integ=%d .arr=%s\n", f("1").integ, f("1").arr);
}
is this case the same as given in arrays that are not lvalues and sequence point restriction and Undefined behavior: when attempting to access the result of function call ? (the value returned are obviously impementation dependend (endiannes) but that is not the issue here).