Is access to the returned union field legal without a variable?

I have a function returning a union type. Whether the standard (C99) allows access to the field of the return value directly from the call without copying the value to the variable. Here is an example illustrating 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 call allowed with f().integ ? In my example, this is a union , but the problem is the same for struct . I ask a question because I vividly remember that gcc 3.3 on Solaris did not like this design and would warn like hell. His problem was that he had to generate an internally invisible variable in order to be able to access the struct or union field. Newer compilers do not seem to mind the construction, but I would like to know if there is a hidden catch (i.e. undefined bevaviour that I did not think about.

EDIT: Okay, it looks like my far-fetched example is too simple, and as commentator 2501 pointed out, pointing to an array decaying into a pointer to objects of scope, let's see if we are in the same situation if I change a little 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); } 

in this case, the same as that specified in arrays that are not length values ​​and sequence point restrictions and Undefined: when trying to access the result of a function call ? (the return value clearly depends on the dependency (endiannes), but that is not the problem here.)

+6
source share
2 answers

This is permissible and permitted by the c standard, and there is no undefined behavior in this code.

EDIT: For fragment

  int main(void) { printf(" thinga.integ=%d .arr=%s\n", f("1").integ, f("1").arr); } 

f("1").arr refers to the union arr element. Since arr is an array and in accordance with rule C, in this context the array will decay to a pointer to its first element. Since t is local to the function (automatic local variable and will no longer exist after the function returns), access to the arr elements will cause undefined behavior.

+3
source

It is just identical.

 printf("thinga is %d\n", (union thinga) {.integ = 1}.integ); 

which is obviously defined correctly.

0
source

All Articles