C++ allows you to declare a variable outside of any
function. Such as a variable is referred to as a global variable (). To
declare a global variable, proceed as you normally would. Here is an
example:
#include <iostream>
using namespace std;
double number;
int main()
{
return 0;
}
After declaring the variable, you can initialize it
immediately:
#include <iostream>
using namespace std;
double number = 3.14159;
int main()
{
cout << "Number = " << number << "\n";
return 0;
}
You can also initialize it inside of the function that
would use it. After declaring and initializing the variable, you can
access its value and use it. For example, you can display its value to the
user. Here is an example:
#include <iostream> using namespace std; double number; int main() { number = 3.14159; cout << "Number = " << number << "\n"; return 0; }
In C++ (some other languages don't have this
situation), the compiler always proceed in a top-down approach. After
declaring a variable, only the sections under it can access it. This means
that you cannot access a variable above its declaration. Consider the
following program where only the area of the declaration has changed:
#include <iostream>
using namespace std;
int main()
{
number = 3.14159;
cout << "Number = " << number << "\n";
return 0;
}
double number;
This program would not compile. The reason is
that, when accessing it inside of main(), as far as main() is concerned,
the variable has never been declared and C++ doesn't allow the use of a
variable before it has been declared. Therefore, you must always declare a
variable before accessing it.
|
|
Namespaces
|
Introduction
|
A namespace is a section of code, delimited and referred to using a
specific name. A namespace is created to set apart a portion of code
with the goal to reduce, otherwise eliminate, confusion. This is done by
giving a common name to that portion of code so that, when referring to
it, only entities that are part of that section would be
recognized.
A namespace is not a variable. It is not a
function. It is not a class. It is only a technique of naming a section
of code and referring to that section of code with a name.
|
Creating a namespace
|
The syntax of creating a namespace is:
namespace Name { Body }
The creation of a namespace starts with the (required)
namespace keyword followed by a name that would identify the section of code. The name follows the rules we have been applying to C++
names except that, throughout this site, the name of a namespace will
start in uppercase.
A namespace has a
body: this is where the entities that are part of the namespace
would be declared or defined. The body of the namespace starts with an
opening curly bracket “{” and ends with a closing curly bracket “}”.
Here is an example of a simple namespace:
namespace Mine { int a; }
The entities included in the body of a namespace are referred to as its members.
|
Accessing a namespace: The Scope Access Operator
|
To access a member of a namespace, there are various techniques you can
use. The scope access operator “::” is used to access the members of a
namespace. To do this, type the name of the namespace, followed by the
scope access operator “::”, followed by the member you are want to
access. Only the members of a particular namespace are available when
using its name. For example, to access the member “a” of the Mine
namespace above, you can write:
Mine::a;
Once you have access to a namespace member, you can initialize it or display its value using
cout. Here is an example:
|
#include <iostream> using namespace std; namespace Mine { int a; } int main() { Mine::a = 140; cout << "Value of a = " << Mine::a << endl; return 0; }
This would produce:
Value of a = 140
When creating a namespace, you can add as many members as you see fit. When necessary, you can use the scope access operator
"::" to call anyone of them as needed. Here is an example:
|
#include <iostream> using namespace std; namespace InterestAndDiscount { double principal; double rate; int periods; } int main() { InterestAndDiscount::principal = 3250; InterestAndDiscount::rate = 0.1225; // =12.25% InterestAndDiscount::periods = 2; cout << "Loan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: " << InterestAndDiscount::rate*100 << "%"; cout << "\nTime: " << InterestAndDiscount::periods << " years" << endl; return 0; }
You can also request the values of the members of a namespace from the user. Remember to use the scope access operator
"::" whenever you need to access the member of a namespace. Here is an example:
|
#include <iostream> using namespace std; namespace InterestAndDiscount { double principal; double rate; int periods; } int main() { cout << "Interest and Discount\n"; cout << "Principal: $"; cin >> InterestAndDiscount::principal; cout << "Rate (example 8.75): "; cin >> InterestAndDiscount::rate; cout << "Number of Years: "; cin >> InterestAndDiscount::periods; cout << "\nLoan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: " << InterestAndDiscount::rate << "%"; cout << "\nPeriods: " << InterestAndDiscount::periods << " years" << endl; return 0; }Here is an example of running the program:
Interest and Discount Principal: $12500 Rate (example 8.75): 7.25 Number of Years: 10 Interest Calculation Principal: $12500.00 Rate: 7.25% Periods: 10 years
The member variable of a namespace can also be mixed with a variable
that is locally declared in a function. All you have to do is make sure
that you qualify the member of the namespace so the compiler would be
able to locate it. Here is an example:
|
#include <iostream> using namespace std; namespace InterestAndDiscount { double principal; double rate; int periods; } int main() { double interest; double maturityValue; cout << "Interest and Discount\n"; cout << "Principal: $"; cin >> InterestAndDiscount::principal; cout << "Rate (example 8.75): "; cin >> InterestAndDiscount::rate; cout << "Number of Years: "; cin >> InterestAndDiscount::periods; interest = InterestAndDiscount::principal * (InterestAndDiscount::rate/100) * InterestAndDiscount::periods; maturityValue = InterestAndDiscount::principal + interest; cout << "\nLoan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: " << InterestAndDiscount::rate << "%"; cout << "\nPeriods: " << InterestAndDiscount::periods << " years"; cout << "\nInterest: $" << interest; cout << "\nMaturity Value: $" << maturityValue << "\n\n"; return 0; }
The using Keyword
|
The scope access operator “::”provides a safe mechanism to access the
members of a namespace. If the namespace is very long and the
application needs constant access, this might be a little cumbersome.
Another technique used to access the members of a namespace involves
using two keywords:
using and namespace.
To call a namespace, on the section of the program where you need to access the members, type:
using namespace NamespaceName;
Both the using and the namespace keywords are required by the compiler. The
NamespaceName represents the name of the namespace whose
member(s) you want to access. Using this technique, the above program can be written:
|
#include <iostream> using namespace std; namespace InterestAndDiscount { double principal; double rate; int periods; } int main() { using namespace InterestAndDiscount; double interest; double maturityValue; cout << "Interest and Discount\n"; cout << "Principal: $"; cin >> principal; cout << "Rate (example 8.75): "; cin >> rate; cout << "Number of Years: "; cin >> periods; interest = principal * (rate/100) * periods; maturityValue = principal + interest; cout << "\nLoan Processing"; cout << "\nPrincipal: $" << principal; cout << "\nRate: " << rate << "%"; cout << "\nPeriods: " << periods << " years"; cout << "\nInterest: $" << interest; cout << "\nMaturity Value: $" << maturityValue << "\n\n"; return 0; }Here is an example of a result:
Interest and Discount Principal: $2500 Rate (example 8.75): 12.15 Number of Years: 4 Loan Processing Principal: $2500 Rate: 12.15% Periods: 4 years Interest: $1215 Maturity Value: $3715
In a variable intensive program (we are still inside of one function
only) where a local variable holds the same name as the member of a
namespace that is being accessed with the using namespace routine, you
will be sensitive to the calling of the same name variable. When
manipulating such a name of a variable that is present locally in the
function as well as in the namespace that is being accessed, the
compiler will require more precision from you. You will need to specify
what name is being called.
|
Combination of Namespaces
|
Introduction
|
Various namespaces can be part of the same file and the same
application. You can create each namespace and specify its own members
in its delimiting curly brackets. With various namespaces on the same
file or application, you can have the same variables in different
namespaces. Here is an example of two namespaces:
|
namespace InterestAndDiscount { double principal; double rate; int periods; double interest; double discount; double maturityValue; } namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; }
To access the member of a namespace, use the scope access operator
appended to its name and call the desired member. Here is an example:
|
#include <iostream> using namespace std; namespace InterestAndDiscount { double principal; double rate; int periods; double interest; double discount; double maturityValue; } namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; } int main() { InterestAndDiscount::principal = 12500; // $ InterestAndDiscount::rate = 8.25; // % InterestAndDiscount::periods = 5; // Years InterestAndDiscount::discount = InterestAndDiscount::rate / 100; InterestAndDiscount::interest = InterestAndDiscount::principal * InterestAndDiscount::discount * InterestAndDiscount::periods; InterestAndDiscount::maturityValue = InterestAndDiscount::principal + InterestAndDiscount::interest; cout << "Interest Calculation"; cout << "\nPrincipal: $" << InterestAndDiscount::principal << "\nRate: " << InterestAndDiscount::rate << "%" << "\nDiscount: " << InterestAndDiscount::discount << "\nPeriods: " << InterestAndDiscount::periods << " years" << "\nInterest: $" << InterestAndDiscount::interest << "\nMaturity Value: $" << InterestAndDiscount::maturityValue; BuyAndSell::originalPrice = 250; // $ BuyAndSell::taxRate = 16.00; // % BuyAndSell::discount = 20.00; // % BuyAndSell::taxAmount = BuyAndSell::originalPrice * BuyAndSell::taxRate / 100; BuyAndSell::discountAmount = BuyAndSell::originalPrice * BuyAndSell::discount / 100; BuyAndSell::netPrice = BuyAndSell::originalPrice + BuyAndSell::taxAmount - BuyAndSell::discountAmount; cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << BuyAndSell::originalPrice << "\nDiscount: $" << BuyAndSell::discountAmount << "\nTax Rate: " << BuyAndSell::taxRate << "\nTax Amount: $" << BuyAndSell::taxAmount << "\nNet Price: $" << BuyAndSell::netPrice << "\n\n"; return 0; }
Using the scope access operator like that, you can perform any operation
on any member of one namespace applied to a member of another
namespace.
We saw earlier that the using namespace
routine allows accessing the members of a namespace. After typing it, if
the name of a variable appears under a using namespace, the compiler
would need to reconcile or identify it; if the name of such a variable
is not recognized as part of the namespace that is being accessed, the
program would not compile. For example, here is an example that uses two
using namespace routines:
|
#include <iostream> using namespace std; namespace InterestAndDiscount { double principal; double rate; int periods; double interest; double discount; double maturityValue; } namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; } int main() { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years discount = rate / 100; interest = principal * discount * periods; maturityValue = principal + interest; cout << "Interest Calculation"; cout << "\nPrincipal: $" << principal << "\nRate: " << rate << "%" << "\nDiscount: " << discount << "\nPeriods: " << periods << " years" << "\nInterest: $" << interest << "\nMaturity Value: $" << maturityValue; using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % discount = 20.00; // % taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount; cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n"; return 0; }
The above program would not compile because the compiler does not understand what
discount is being referred to in the second discount call: is it
InterestAndDiscount::discount or BuyAndSell::discount?
If you want to use different namespaces with the using namespace
routine, each namespace will have to control its scope. One solution
would be to create a “physical” scope for each namespace. Here is an
example:
|
#include <iostream> using namespace std; namespace InterestAndDiscount { double principal; double rate; int periods; double interest; double discount; double maturityValue; } namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; } int main() { { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years discount = rate / 100; interest = principal * discount * periods; maturityValue = principal + interest; cout << "Interest Calculation"; cout << "\nPrincipal: $" << principal << "\nRate: " << rate << "%" << "\nDiscount: " << discount << "\nPeriods: " << periods << " years" << "\nInterest: $" << interest << "\nMaturity Value: $" << maturityValue; } using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % discount = 20.00; // % taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount; cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n"; return 0; }
Before creating a “physical” scope, we saw that the compiler is able to
point out what problem occurred at compilation
time. Fortunately, the compiler is able to explicitly designate what
problem it encountered. In this case there is a conflict in name
resolution: two namespaces have a member of the same name.
The solution, which is commonly used, is to qualify the variable that is causing the conflict. You
may want to qualify only the second discount call because the compiler will
associate the first discount call with the first using namespace. The safest way is to qualify both calls to the
discount variable, as follows:
|
#include <iostream> using namespace std; namespace InterestAndDiscount { . . . } namespace BuyAndSell { . . . } int main() { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years InterestAndDiscount::discount = Rate / 100; interest = principal * InterestAndDiscount::discount * periods; maturityValue = principal + interest; cout << "Interest Calculation"; cout << "\nPrincipal: $" << Principal << "\nRate: " << Rate << "%" << "\nDiscount: " << InterestAndDiscount::discount << "\nPeriods: " << periods << " years" << "\nInterest: $" << interest << "\nMaturity Value: $" << maturityValue; using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % BuyAndSell::discount = 20.00; // % taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * BuyAndSell::discount / 100; netPrice = originalPrice + taxAmount - discountAmount; cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n"; return 0; }
Nesting Namespaces
|
Nesting a namespace is the ability to include a namespace inside (as
part of the body) of another namespace. To do this, create the intended
namespace as a member of the parent namespace. The nested namespace
should have its own name and its own body. Here is an example:
|
namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; { long itemNumber; } }
To access a member of a nested namespace, first call its parent, type
the :: operator, type the name of the nested namespace, followed by the
:: operator, then type the name of the variable you are trying to
access. Here is an example:
|
#include <iostream> using namespace std; namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID { long itemNumber; } } int main() { BuyAndSell::originalPrice = 780.50; BuyAndSell::taxRate = 7.55; BuyAndSell::discount = 25; // % BuyAndSell::ItemID::itemNumber = 641238; BuyAndSell::taxAmount = BuyAndSell::originalPrice * BuyAndSell::taxRate / 100; BuyAndSell::discountAmount = BuyAndSell::originalPrice * BuyAndSell::discount / 100; BuyAndSell::netPrice = BuyAndSell::originalPrice + BuyAndSell::taxAmount - BuyAndSell::discountAmount; cout << "Buy and Sell - Receipt"; cout << "\nItem Nunmber: " << BuyAndSell::ItemID::itemNumber; cout << "\nOriginal Price: $" << BuyAndSell::originalPrice; cout << "\nDiscount: $" << BuyAndSell::discountAmount; cout << "\nTax Rate: " << BuyAndSell::taxRate; cout << "\nTax Amount $" << BuyAndSell::taxAmount; cout << "\nNet Price: $" << BuyAndSell::netPrice << "\n\n"; return 0; }
Following the same logic, you can have as many namespaces and as many
nested namespaces in your application as you desire. If you nest a
namespace, you can use as many
"::" operators to qualify each member of the nested namespace as you
want. Here is an example:
|
#include <iostream> using namespace std; namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID { long itemNumber; namespace DateSold { int month; int Day; int Year; } } } int main() { . . . BuyAndSell::ItemID::DateSold::month = 10; BuyAndSell::ItemID::DateSold::day = 18; BuyAndSell::ItemID::DateSold::year = 2002; . . . return 0; }You can also use the using namespace routine by calling each namespace using its complete name:
#include <iostream> using namespace std; namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID { long itemNumber; namespace DateSold { int month; int day; int year; } } } int main() { using namespace BuyAndSell; using namespace BuyAndSell::ItemID; using namespace BuyAndSell::ItemID::DateSold; originalPrice = 780.50; taxRate = 7.55; discount = 25; // % itemNumber = 641238; taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount; month = 10; day = 18; year = 2002; cout << "Buy and Sell - Receipt"; cout << "\nReceipt Date: " << month << "/" << day << "/" << year; cout << "\nItem Nunmber: " << itemNumber; cout << "\nDiscount Category: " << qualifyForDiscount; cout << "\nOriginal Price: $" << originalPrice; cout << "\nDiscount: $" << discountAmount; cout << "\nTax Rate: " << taxRate; cout << "\nTax Amount $" << taxAmount; cout << "\nNet Price: $" << netPrice << "\n\n"; return 0; }
Otherwise, you can create a using namespace for each namespace and make
sure that each one of them controls its scope. As long as you are using
the scope access operator to identify the variable that is being
accessed inside of a using namespace, you can call the member of any
namespace in any scope, provided you qualify it.
|
The std Namespace
|
To avoid name conflicts of the various items used in its own implementation, the C++ Standard provides a namespace called
std. The std namespace includes a series of libraries that you will routinely and regularly use in your programs.
The following libraries are part of the std namespace:
|
|
The following additional libraries can be used to include C header files into a C++ program:
|
Therefore, whenever you need to use a library that is part of the
std namespace, instead of typing a library with its file extension, as in
iostream.h, simply type the name of the library as in iostream. Then, on the second line, type
using namespace std;
As an example, instead of typing
#include <iostream.h>
You can type:
|
#include <iostream> using namespace std;
Because this second technique is conform with the C++ Standard, we will use it whenever we need one of its libraries.
No comments:
Post a Comment