{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

cs31 lecture 17

If the variable is not defined in the current

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ble can only be declared once in the Rule: program program x To refer to this variable from another file: extern <vardecl> 73 Namespaces again x Global variables can be declared in a namespace x Typedefs can be declared in a namespace x In both cases, the using directive and :: operator can be In used used x Be careful: namespaces are not classes! instance of a class: an object (with its own data)
 Namespace: simple “prefix” in the names of functions/global Namespace: variables/type declarations variables/type 74 Scopes in C++ x A variable is accessible only from within its scope x Scope: region (typically a block enclosed with {} )
 where Scope: the variable exists the x Examples: for (int i = 0; i < N; ++i)
 sum += i; sum foo = i; // <- invalid statement: i is not defined 75 The intuition behind scopes x A program can be seen as a hierarchy of regions x A variable declared in a region can be used only from variable within this region and all its subregion within x From a (sub-)
region, the closest definition of the variable From applies. If the variable is not defined in the current subapplies. region, then a definition is searched for in the parent region, region, etc. region, 76 Example: foo.cpp // region 1 starts iint foo()
 nt { /// region 1.1 starts. / int i = 42; int { /// region 1.1.1 starts. Parents: 1.1, and 1 / float i = 0; float /// region 1.1.1 ends / } { /// region 1.1.2 starts. Parents: 1.1, and 1 / /// region 1.1.2 ends / } /// re...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online