20.2.2.1. Exercises: File Scope Versus Block Scope and operator::

  1. Determine the scope of each of the variables in Example 20.7.

  2. Be the computer and predict the output of the program.

[ fromfile: scopestorage.xml id: None ]

Example 20.7. src/early-examples/scopex.cpp

#include <iostream>
using namespace std;

long x = 17; 
float y = 7.3;              1
static int z = 11;          2

class Thing {
    int m_Num;              3
public:
    static int s_Count;     4
    Thing(int n = 0) : m_Num(n) {++s_Count;}
    ~Thing() {--s_Count;}
    int getNum() { return m_Num; }
};

int Thing::s_Count = 0;
Thing t(11);

int fn(char c, int x) {     5
    int z = 5;              6
    double y = 6.933; 
    { char y;               7
    Thing z(4);             8
    y = c + 3; 
    ::y += 0.3;             9
    cout << y << endl;      10
    }
    cout << Thing::s_Count
         << endl;           11
    y /= 3.0;               12
    ::z++;                  13
    cout << y << endl;
    return x + z;
}

int main() {
    int x, y = 10; 
    char ch = 'B';          14
    x = fn(ch, y); 
    cout << x << endl; 
    cout << ::y << endl;    15
    cout << ::x / 2 << endl;
    cout << ::z << endl;
}

1

Scope: ________________

2

Scope: ________________

3

Scope: ________________

4

Scope: ________________

5

Scope: ________________

6

Scope: ________________

7

Scope: ________________

8

Scope: ________________

9

Scope: ________________

10

Scope: ________________

11

Scope: ________________

12

Scope: ________________

13

Scope: ________________

14

Scope: ________________

15

Scope: ________________

<include src="src/early-examples/scopex.cpp" href="src/early-examples/scopex.cpp" id="scopexcpp" mode="cpp"/>