70 likes | 88 Views
Scope – Kudos to Dr. Mullins. The section of the program where a variable is valid (known or visible). local = available to only one function or block. Used to limit access. global = available to multiple functions or blocks. Used to save call time or reduce complexity of call sequence.
E N D
Scope – Kudos to Dr. Mullins • The section of the program where a variable is valid (known or visible). • local = available to only one function or block. Used to limit access.global = available to multiple functions or blocks. Used to save call time or reduce complexity of call sequence.
Scope Block = { } Local:The scope of an identifier declared inside a block extends from the point of declaration to the end of that block. Global:The scope of an identifier declared outside all functions and classes extends from the point of declaration to the end of the source file. * *
Local Variables • declared within a function definition • private to a function definition • variables in different functions are totally independent • different functions can have variables with the same names; however, each variable will have its own memory address • actually applies to any block * * * * *
int x = 3;// global because before main • void myfunction( ); // prototype • void main(void) • { // no variables local to main( ) • cout <<"x = "<<x<<" before the function call.\n"; • myfunction( ); • cout <<"x = "<<x<<" after the function call.\n"; • } • void myfunction( ) • { • int r; // local to myfunction( ) • r = ++x; • cout <<"r = "<<r<<" within the function.\n"; • }
Scope & Globals x 3 main () myfunction() myfunction() r
Scope & Globals x = 3 before the call r = 4 within function x 3 4 myfunction() cout << x;myfunction(); main() r 4 r = ++x; myfunction() cout << r;
Scope & Globals x = 3 before the call r = 4 within function x x = 4 after the call 4 myfunction() cout << x; main() Side Effects r myfunction()