yogi
yogi

Reputation: 53

how to is any variable accessed outside the block when "return" is used?

I am beginner in C and have started writing code in c. I am having doubts regarding the scope of variables. When any variable is written inside the block then its scope is inside that block. But, when return word is used how is the variable accessed outside the block?

Example:

int add(int a, int b) 
{
    int c;//scope of c is within this block
    c=a+b;
    return c;
} //it ends here

void main()
{
    int answer;
    answer=add(2,3);//how we gets  value  of "c " here
    printf("%d",answer);
}

Upvotes: 2

Views: 160

Answers (3)

Olayinka
Olayinka

Reputation: 2845

You should also ask how function arguments go from scope to scope? If I declare/initialize a variable in main(), how can I use the argument in a function outside main's scope?

When you you call a function with arguments, the arguments are copied and sent to the functions. Even if they are pointer arguments, they are also copied. And when the function returns a value, the value is copied and sent back to whatever calls the function.

This is only from my C and C++ knowledge.

Upvotes: 0

No Idea For Name
No Idea For Name

Reputation: 11597

when you write a function in c and return a value The value for c is held in a temporary location (called a stack) and then that temporary location is copied to a after c is no longer available. For a more general discussion on this "stacks", Google on "Push Down Pop Up Stacks"

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

therefor it's not a scope issue. the value is just passed to answer

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182829

It isn't accessed outside the block. When you do return c;, a copy of c's value is returned, not c itself.

int foo()
{
   int c = 3;
   return c;
}

This just returns 3, the value c holds.

Some languages permit the compiler to "cheat" by extending c's scope, but this is an optimization and doesn't change the logic.

Upvotes: 6

Related Questions