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 a
struct
in above example ), and how to properly access them ?
Where ends lifetime of a return
value ?
A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.
C/C++ use lexical scoping. The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."
The lifetime of a variable is the time during which the variable stays in memory and is therefore accessible during program execution. The variables that are local to a method are created the moment the method is activated (exactly as formal parameters) and are destroyed when the activation of the method terminates.
The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details.
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.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 the printf
function call. When the printf
function returns, that temporary object is destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With