I read about the return
values between function calls,
and experimented with the following code snippet :
/* file structaddr.c */
#include <stdio.h>
#define MSIZE 10
struct simple
{
char c_str[MSIZE];
};
struct simple xprint(void)
{
struct simple ret = { "Morning !" };
return ret;
}
int main(void)
{
printf("Good %s\n", xprint().c_str);
return 0;
}
The code is compiled without errors and warnings .
Tested with GCC 4.4.3 (Ubuntu 4.4.3-4ubuntu5.1) and Visual C++ compilers .
gcc -m32 -std=c99 -Wall -o test structaddr.c
cl -W3 -Zi -GS -TC -Fetest structaddr.c
Output :
Good Morning !
I'm a little confused by the result .
The code is written correctly ?
My Question :
What is the visibility of the function
return
value( array from astruct
in above example ), and how to properly access them ?Where ends lifetime of a
return
value ?
The function
xprint
returns a copy of the structure, and the compiler stores this copy in a temporary, and the temporaries lifetime is the duration of theprintf
function call. When theprintf
function returns, that temporary object is destroyed.In C, the lifetime of the temporary in your example ends when the
printf
expression is finished:printf
expression is finished.In C++, the lifetime in your example is the same as in C:
printf
expression.