↻ back to index

Lab 4: Names and Scopes in C++

Purpose

This lab's purpose is to show how names and scopes work in C++. This will be demonstrated with the compiling and testing of several C++ programs. These programs were downloaded and instructions followed off Richard Botting's assignment website.

Testing

simple.cpp

This program will test the scope of the redefinitions of integer "i". It has a global scope defined as 2 and two more inner scopes.

Output:
i=1
i=2
  i=3
    i=4
  i=4
i=4
		

It appears that i has been redefined in different scopes with later scopes overwriteing the original value of "i", defined in the global scope.

tooSimple.cpp

Output:
i=1
i=1
j=2
  i=1
  j=2
  k=3
i=1
j=2
	    

Like the last one, but this time there are locally declared variables like "k". Only blocks that the variable was declared in are able to call the variables and they can call global variables like i. Otherwise, these local variables cannot be referred to outside of its scope.

simple2.cpp

Output:
i=1
i=2
  i=3
  i=3
i=2
  i=4
i=2
	    

Here we have a globally-scoped variable "i" that is defined globally to 2. Then there are two locally-declared variables also named "i" that equals different values. In the end, the global variable "i" still equals 2 after the other "i"s were declared.

simpleScopes.cpp

Output:
i=1
i=2
  i=3
    i=4
  i=3
i=2
	    

This program also demonstrates variables of the same name but different scopes carrying different values.

scopes.cpp

Output:
Global i =1
Main i =2
Inner i =3
staticScoped(1) i= 1
dynamicScoped(1) i= 3
Outer i=2
staticScoped(2) i= 1
dynamicScoped(2) i= 2
	    

It appears that the same test is applied but a macro and a function are used to output different instances of i. It appears that the macro function outputs the instance of i that it occurs in. For the function called "staticScoped" the i is the gloabally declared instance of i.

Conclusion

How names and scopes work in C++ is very interesting. A C++ program can indeed have variables of the same name and different values but they have to be of different scopes. When "cout" is called on i, the program outputs the instance of i that exists in the same scope of it or else it outputs i's of a wider scope. For example, a "cout" function in the same text block as a declaration of i will output the value of that i. Since all C++ programs must be declared globally, since "staticlyScoped" has no instance of i inside it, it outputs the global i instead. "dynamicScoped" however is a macro, so it works like a normal line of code for outputting i.