Variable Scope

Variable Scope

FUNCTIONS AND VARIABLE SCOPE Each function defines a new, unique scope Delroy A. Brinkerhoff SCOPE • Scope is the location in a program where an identifier is visible or accessible • Named scopes • Global • Class • Local • Block / control statement • Scope resolution takes place from the tightest to the widest GLOBAL VARIABLES AND FUNCTION COUPLING • Functions that only operate on parameter values can be tested independently • Functions that share data through global variables are coupled and must be tested together • The level of complexity increases rapidly as each new coupled function is added • The complexity of coupled functions limit the size of programs VISUALIZING THE COMPLEXITY OF COUPLED FUNCTIONS VISUALIZING THE COMPLEXITY OF COUPLED FUNCTIONS VISUALIZING THE COMPLEXITY OF COUPLED FUNCTIONS CLASS SCOPE • One of the many advantages of the object-oriented programming model is that it provides an intermediate scope (between global and local) • Some functions can see or access class scope variables or data • Class scope variables are hidden from most of the program • Covered in greater detail later LOCAL VARIABLES • Variables defined inside of a function; includes function parameters double average(...) int to_seconds(int hrs, { int mins, int secs) double sum = 0; { . int h = hrs * 3600; . int m = mins * 60; . return h + m + secs; } } double average() { double sum = 0; int count = 0; while (...) BLOCK SCOPE { int data; The scope of the for-loop loop control variable is restricted to the for-loop cin >> data; sum += data; count++; } return sum / count; } SCOPE RESOLUTION • The compiler searches for variables from int nlines = 10; the tightest to the widest scope int counter = 100; // global void function( ) { int counter = 200; // local cout << "nlines " << nlines << "counter " << counter; } STATIC VARIABLES double average() double random() { { double sum = 0; static double x = 0; int count = 0; . x = x * (x + 1) % 2147483648L; return sum / count; return x; } } EXTERN VARIABLES file1.cpp file2.cpp int counter = 100; extern int counter; void increment() int report() { { counter++; return counter; } }.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    12 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us