1
2
3
4
5
6
7
8
| int main() { // start a block // multiple statements int nValue = 0; return 0; } // end a block |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| #include <iostream> int main() { using namespace std; cout << "Enter a number: " ; int nValue; cin >> nValue; if (nValue > 0) { // start of nested block cout << nValue << " is a positive number" << endl; cout << "Double this number is " << nValue * 2 << endl; } // end of nested block } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| int main() { using namespace std; cout << "Enter a number: " ; int nValue; cin >> nValue; if (nValue > 0) { if (nValue < 10) { cout << nValue << " is between 0 and 10" << endl; } } } |
1
2
3
4
5
6
7
8
9
10
| int main() { // start main block int nValue = 5; // nValue created here double dValue = 4.0; // dValue created here return 0; } // nValue and dValue destroyed here |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| void someFunction() { int nValue; } int main() { // nValue can not be seen inside this function. someFunction(); // nValue still can not be seen inside this function. return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
| int main() { int nValue = 5; { // begin nested block double dValue = 4.0; } // dValue destroyed here // dValue can not be used here because it was already destroyed! return 0; } // nValue destroyed here |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| int main() { // start outer block using namespace std; int x = 5; { // start nested block int y = 7; // we can see both x and y from here cout << x << " + " << y << " = " << x + y; } // y destroyed here // y can not be used here because it was already destroyed! return 0; } // x is destroyed here |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| int main() { // outer block int nValue = 5; if (nValue >= 5) { // nested block int nValue = 10; // nValue now refers to the nested block nValue. // the outer block nValue is hidden } // nested nValue destroyed // nValue now refers to the outer block nValue return 0; } // outer nValue destroyed |
1
2
3
4
5
6
7
8
9
10
| int main() { // do not declare y here { // y is only used inside this block, so declare it here int y = 5; cout << y; } // otherwise y could still be used here } |
0 comments: