C/c

Advertisement


Question
hi sir!i know the storage classes.but i am not able to identify the difference between life and scope of a variable.
can you show the difference  with simple programmes?

Answer
Hi phaneendra

In C all variables are either local or global.

Global variables are ones which are declared outside of any function. They are in scope and alive for as long as the program is running. In scope means that they can be accessed, and alive means that they exist. In the case of global variables, scope, and lifetime mean the same thing.


Local variables are declared in functions. Imagine a function is a box and the box exists from the time the function is entered until the function exits. The variables are in the box. One more thing. When the first function calls a second function, the first box is closed and placed inside the second box. The variables in the first box still exist, but now that we're in the second function, the first box is closed and the variables cannot be seen so they are not in scope. When the second function returns, to the first function, the first box is opened again and the variable are again visible or in scope. When a function returns, the box is destroyed and its variables stop existing. They are neither in scope nor alive.

Consider the following 2 functions.

function1
{
  int x;
  / The variable y in function 2 does not exist yet */
  function2()
  /* The variable y in function 2 no longer exists */
}

function2() /* called from function 1 */
{
  int y;
  /* here function 2 is called from function 1. The variable x in function 1
  exists still, but is not visible. It is not in scope. Only y is in scope
*/
}


Actually, functions are not the only scope-blocks. Any code between {} brackets is a scope block and variables declared in the block cannot be seen outside of the block

for example
function3()
{
  int a;
  {
      int b;
      // a and b in scope here
  }
  // b no longer in scope. It might not even exist anymore.
}

I hope that makes thing clearer.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.