30 likes | 124 Views
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)
E N D
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!!!
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; }