Created
September 25, 2013 16:50
-
-
Save natemcmaster/6702531 to your computer and use it in GitHub Desktop.
Tutoring: demonstration of variable scope in C++;
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
void someFunction(); | |
int number = 0; // Scoped globally (everywhere inside this C++ program) | |
int main(){ | |
cout << number << endl; // Prints 0. Refers to global#number | |
int number = 2; // Scoped to main() | |
cout << number << endl; // Prints 2. Refers to main#number | |
{ // Brackets create a new scoping level. Let's call this submain. | |
number = 4; // Modifies the next scope level up, main#number | |
cout << number << endl; // Prints 4. Refers to main#number | |
int number = 5; // Scoped to submain | |
cout << number << endl; // Prints 5. Refers to submain#number | |
int prime = 7; // Also scopped to submain | |
cout << prime << endl; // Prints 7 | |
} | |
cout << prime << endl; // When compiling, g++ will say "error: 'prime' was not declared in this scope" | |
cout << number << endl; // Prints 4. Refers to main#number | |
someFunction(); | |
/* | |
(Without line 33, the program compiles and prints the following numbers in this order) | |
0 | |
2 | |
4 | |
5 | |
7 | |
4 | |
0 | |
88 | |
*/ | |
return 0; | |
} | |
void someFunction(){ | |
cout << number << endl; // Prints 0. Refers to global#main | |
int number = 88; // Scopped to someFunction(); | |
cout << number << endl; //Prints 88. Refers to someFunction#number | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment