1 / 9

Engineering 1020

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.

buzz
Download Presentation

Engineering 1020

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Engineering 1020 Introduction to Programming Peter King peter.king@mun.ca www.engr.mun.ca/~peter Winter 2010

  2. 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.

  3. 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

  4. 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 }

  5. 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 }

  6. 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

  7. 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.

  8. 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

  9. ENGI 1020: Design Online example

More Related