Docsity

Understanding Variable Scope in C++, Slides of Computer Engineering and Programming

Partial preview of the text

Download Understanding Variable Scope in C++ and more Slides Computer Engineering and Programming in PDF only on Docsity!

  • Lecture
  • The "scope" of a variable is the region within a

program where that variable name is defined.

  • A variable that is declared before any statements

which define a function (such as " void main ( ) " ) has file scope. That is, its name, its designated memory location, and any value assigned to it will be known throughout the main function and any other function (subprogram) in the same file of source code.

  • The same variable name can not be defined (declared) twice within the same block of code. A block of code is the code inside of a set of braces { }. However, a variable in C++ can be declared in other blocks of code (and even within nested blocks).
  • If the same variable name is declared in multiple nested blocks of code, the declaration that is within the particular block of code that is being executed at that time is the one that is currently "in scope" or in effect.

Scope of Variables Example

  • The following program will not compile

because x is only defined inside the if block of

statements and is not known outside that

block (neither before nor after it).

#include <stdio.h> int main ( ) { int x = 3 ; /* Now "x" known, program compiles */ FILE *fptr ; fptr = fopen ("scope.dat", "w") ; fprintf (fptr, ”before if block, x=%d\n", x) ; if ( x == 3 ) { float x = 4.5 ; fprintf (fptr, "inside if block, x=%f\n", x) ; } fprintf (fptr, "after if block, x=%d\n", x) ; }

  • When the program is modified as was shown on

the previous slide, x is known throughout the program, but the x inside the if block of statements has a different data type and has a different value than the one outside the block.

  • These two versions of the variable, x , have two

different memory locations, and thus we have two completely different variables with the same name. (Confusing, eh?)