Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating and Using Namespaces 641

18


The first intdefinition,globalScopeInt, on line 1 is visible within the functions
f()and main(). The next definition is found on line 4 within the function f()
and is named localScopeInt. This variable has local scope, meaning that it is visible
only within the block defining it.
The main()function cannot access f()’s localScopeInt. When the f()function returns,
localScopeIntgoes out of scope. The third definition, also named localScopeInt,is
found on line 8 of the main()function. This variable has block scope.
Note that main()’s localScopeIntdoes not conflict with f()’s localScopeInt. The next
two definitions on lines 10 and 11,anotherLocaland localScopeInt, both have block
scope. As soon as the closing brace is reached on line 12, these two variables lose their
visibility.
Notice that this localScopeIntis hiding the localScopeIntdefined just before the
opening brace (the second localScopeIntdefined in the program). When the program
moves past the closing brace, the second localScopeIntdefined resumes visibility. Any
changes made to the localScopeIntdefined within the braces does not affect the con-
tents of the outer localScopeInt.

Linkage ..........................................................................................................


Names can haveinternaland external linkage. These two terms refer to the use or avail-
ability of a name across multiple translation units or within a single translation unit. Any
name having internallinkage can only be referred to within the translation unit in which it
is defined. For example, a variable defined to have internal linkage can be shared by func-
tions within the same translation unit. Names having externallinkage are available to
other translation units. Listings 18.4a and 18.4b demonstrate internal and external linkage.

LISTING18.4A Internal and External Linking


0: // file: first.cpp
1: int externalInt = 5 ;
2: const int j = 10 ;
3: int main()
4: {
5: return 0 ;
6: }

LISTING18.4B Internal and External Linking


0: // file: second.cpp
1: extern int externalInt ;
2: int anExternalInt = 10 ;
3: const int j = 10 ;

ANALYSIS
Free download pdf