Download as pdf
Download as pdf
You are on page 1of 2

Question 7

C++ Assignment

Q.7: State the difference between life and scope of variable with the help of example. Explain local,
global and static variable.

Answer:

SCOPE OF VARIABLES
All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, at the beginning of the body of the function main when we declare a, b, and result were of type int or in the function. A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.

Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration. The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa.

A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static. A local static variable is a variable that can maintain its value from one function call to another and it will exist until the program ends.

09CE37 19

Question 7

C++ Assignment

When a local static variable is created, it should be assigned an initial value. If it's not, the value will default to 0.The following example sets a static local, called TheLocal, to the value 1000. void main(void){ static int TheLocal; TheLocal=1000; } /* a static local variable*/

A global static variable is one that can only be accessed in the file where it is created. This variable is said to have file scope The following example also sets a global, called TheGlobal, to the value 1000 static int TheGlobal; / * a static global variable*/ void main(void){ TheGlobal=1000; }

09CE37 20

You might also like