caesar
caesar

Reputation: 3135

scope or lifetime of variable in C

I have a question about scope or lifetime of variables, let me explain my question with an example.The code below, I've created a local variable c and returned it. In main() function the line a=foo(), I think since c is a local variable and the function foo() was done, the memory cell for variable c should have been destroyed and the variable a should have been kept garbage value.However it keeps 1. Where am I wrong is there anyone to help me ? Thanks in advance.

#include <stdio.h>
int foo()
{
    int c=1;
    return c;
}


int main()
{
    int a;
    a=foo();
    printf("%d",a);
    return 0;
}

Upvotes: 0

Views: 364

Answers (7)

Amit Chauhan
Amit Chauhan

Reputation: 6889

opps i misunderstood your question in my first reply. actually when you return from any function there are some rules in assembly code.

so it copy value in internal register and then value of this register is copied into a.

Upvotes: 0

d6bels
d6bels

Reputation: 1482

I think since c is a local variable and the function foo() was done, the memory cell for variable c should have been destroyed

Yes, this is likely what happens.

But, your function returns a value, and in this case 1, the value of c.
So however the variable c is freed, that value is returned, it is not lost or freed.

Then you store that value in a and that is why a = 1.

Upvotes: 0

No Idea For Name
No Idea For Name

Reputation: 11597

the memory of c was indeed destroyed when the function was done, but the function returned 1 and that 1 was put in a. the value was copied to the memory of a!

but, for example, this next example will not save the value:

#include <stdio.h>
int foo(int a)
{
    int c=1;
    a = c;
}


int main()
{
    int a = 0;
    a=foo();
    printf("%d",a);
    return 0;
}

will print "0"

Upvotes: 0

user2408578
user2408578

Reputation: 464

its basically a function activation record,which will be pushed on the system stack and when your function is returning it will first copy all values to the return result area,that is nothing but a=foo(); and then it will destroy that function activation record from the system stack,I hope it would help

Upvotes: 1

Lidong Guo
Lidong Guo

Reputation: 2857

When return c; it copy c to a tmporary value .And the then copy the tmporary value to a

Upvotes: 0

ouah
ouah

Reputation: 145899

After foo function returns, object c is destroyed. In the return statement, c object is evaluated and its value is returned. What you are returning is not c object but the value of c.

Upvotes: 0

Amit Chauhan
Amit Chauhan

Reputation: 6889

It is not necessary to make its value garbage. after function collapse allocated memory is getting freed but its value remain same,it does not overwrite value with another garbage value.

Upvotes: 0

Related Questions