lifetime of local variables

  • Thread starter Anargyros L. Papadopoulos
  • Start date
A

Anargyros L. Papadopoulos

int do_sth(int);

int fun_1(int *val, int i = 0)
{
static int *s[3];

if (val && i >= 0 && i < 3) {
s = val;
return 1;
} else {
if (s[0])
do_sth(*s[0]);
return 0;
}
}

int fun_2(void)
{
int v1 = 1, v2 = 2, v3 = 3;

fun_1(&v1, 0);
fun_1(&v2, 1);
fun_1(&v3, 2);


/* ... code ... */

return fun_1(0); // <<<< HERE >>>>
}

- is it guarantee that in the last call of 'fun_1' (return statement)
pointers to v1, v2, v3, that stored into 's' in 'fun_1', are still valid ?
- if yes, any comment is it guarantee and after optimization ??
 
V

Victor Bazarov

Anargyros said:
int do_sth(int);

int fun_1(int *val, int i = 0)
{
static int *s[3];

if (val && i >= 0 && i < 3) {
s = val;
return 1;
} else {
if (s[0])
do_sth(*s[0]);
return 0;
}
}

int fun_2(void)
{
int v1 = 1, v2 = 2, v3 = 3;

fun_1(&v1, 0);
fun_1(&v2, 1);
fun_1(&v3, 2);


/* ... code ... */

return fun_1(0); // <<<< HERE >>>>
}

- is it guarantee that in the last call of 'fun_1' (return statement)
pointers to v1, v2, v3, that stored into 's' in 'fun_1', are still valid ?
- if yes, any comment is it guarantee and after optimization ??


AFA the Standard goes, yes, it's still valid. 'v1', 'v2', 'v3' all live
until the block where they are declared (function body) ends. It does not
end with the 'return' statement executing. It ends when function exits.
Since the evaluation of the return statement expression has to complete
before the function exits, the static pointer array contents inside the
'fun_1' are still valid.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top