1 / 3

Blocks of Code & Scope

Blocks of Code & Scope. Block of Code: Delineated by {}. Style used to date: All local variables are defined/declared at top of function These variables are inside the block of code delineated by the {} of the start and end of the function (including function main)

zarola
Télécharger la présentation

Blocks of Code & Scope

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. Blocks of Code&Scope

  2. Block of Code: Delineated by {} • Style used to date: • All local variables are defined/declared at top of function • These variables are inside the block of code delineated by the {} of the start and end of the function (including function main) • The scope of these variables is limited to the block in which they are declared • Optional style is define variables closer to where they are used • Variables may defined inside any block or set of { } • Scope of the variable defined inside the block is limited to the point of definition till the closing brace of the block • When a block is nested inside another block, any variables defined inside the inner block that have the same name as variables defined outside the block obscure the scope of those outside the block. This is confusing and should be avoided!!!

  3. Example void PrintTicket(int); int main() { int age; cout << “Enter your age: “; cin >> age; if (age < 18) { cout << endl << “You may not purchase a ticket.”; } else { int choice; cout << “1. Matinee $15.45” << endl; cout << “2. Evening $ 21.45” << endl; cout << “Enter your choice: “ cin << choice; PrintTicket(choice); // age is visible here and choice is visible here } // age is visible but choice is no longer visible return 0; }

More Related