90 likes | 258 Views
Engineering 1020. Introduction to Programming Peter King peter.king@mun.ca www.engr.mun.ca/~peter Winter 2010. ENGI 1020: Scope. When we create an identifier (variable, function name), there are limitations on where it can be used.
E N D
Engineering 1020 Introduction to Programming Peter King peter.king@mun.ca www.engr.mun.ca/~peter Winter 2010
ENGI 1020: Scope When we create an identifier (variable, function name), there are limitations on where it can be used. Scope is the region of the program where an identifier can be used.
ENGI 1020: Scope Two main types of scope Local identifiers declared within a code block {} • scope extends to end of block Global identifiers declared outside of any code block • scope extends to end of source file
ENGI 1020: Scope Global scope example //myFunction is declared outside block void myFunction(int a, int b); int main(){ //I can use it here myFunction(1,2); return 0; } //... and here void myFunction(int a, int b){ //do something }
ENGI 1020: Scope Local scope example void myFunction(int a, int b); int main(){ int lVar = 0; //declared in block //I can use it here myFunction(lVar,2); return 0; } void myFunction(int a, int b){ lVar = 5; //Uh oh, can't use it here }
ENGI 1020: Scope Scope allows us to re-use identifiers C++ will assume the most local version of an identifier Visibility is the nature of the compiler focusing on those variables that are in the closest scope See Online examples
ENGI 1020: Scope Try to keep the scope of variables small Prefer local variables over global variables. Use parameters rather than global variables to pass information to functions. If your parameter list is too long maybe your function is doing too much.
ENGI 1020: Design 1. Divide the problem into independent sub-problems that are easier to solve. 2. Start with a high-level solution to the problem, few abstract steps 3. Gradually refine solution into an concrete solution (i.e., algorithm) by adding detail, break high level steps into smaller functional units
ENGI 1020: Design Online example