Docsity

Local, Global, and Static Variables in Programming – Complete Notes, Study notes of Information Technology

Partial preview of the text

Download Local, Global, and Static Variables in Programming – Complete Notes and more Study notes Information Technology in PDF only on Docsity!

Local, Global, and static Local

variables

By Anam Javaid COMSATS University Islamabad, Wah Campus

Scope of a Variable

  • A variable can be declared as a local, a global, or a static local in C++.
  • The scope of a variable is the part of the program where the variable can be referenced.
  • Variable defined inside a function is referred to as a local variable.
  • C++ also allows you to use global variables. They are declared outside all functions and are accessible to all functions in their scope.
  • Local variables do not have default values, but global variables are defaulted to zero.

Example demonstrates the scope of local and

global variables.

output

The Scope of Variables in a for Loop

  • A variable declared in the initial-action part of a for-loop header has its scope in the entire loop.
  • However, a variable declared inside a for-loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable, as shown in

The Scope of Variables in a for Loop

Caution

  • Do not declare a variable inside a block and then attempt to use it outside the block. Here is an example of a common mistake: for (int i = 0; i < 10; i++) { } cout << i << endl;
  • The last statement would cause a syntax error, because variable i is not defined outside the for loop.

Static Local Variables

  • After a function completes its execution, all its local variables are destroyed. These variables are also known as automatic variables. Sometimes it is desirable to retain the values stored in local variables so that they can be used in the next call.
  • C++ allows you to declare static local variables. Static local variables are permanently allocated in the memory for the lifetime of the program. To declare a static variable, use the keyword static.

Class Activity: Print Output

Next Lecture

Default Arguments Inline Functions Function Overloading Call by value, Call by Pointers, and Call by reference