Variables and the Stack

 Variables

 Introduction to Variables

One of the most regular assignments that a computer program is asked to perform consists of displaying things on the monitor screen. The things a program displays are originally created by you; then they can be added, modified or removed by your users. Based on this, in order for your program to display something, you must primarily make it available or create it.

There are mainly two types of things that will display on the screen when your program executes: the things you created and those your user would have added. In the previous lesson, we had a preview of using cout, Write, and WriteLine to display things on the screen. The simplest programs consist of easily displaying things on the screen. Unfortunately, they are usually insignificant. Another of the most significant operations you will perform consists of requesting values from a user. For example, if you write a program that calculates the weekly salary of an employee, in order to make this program usable to many employees, you would have to write it with general requests. On one hand, you would request the number of hours worked for the week and the employees salary. On the other hand, you would calculate the weekly salary and display it, probably along with other pieces of information.

A variable is a value that you want to make available to the program but without primarily knowing what that value is. For example, if you want to write a program that would calculate employees weekly salary, you would not know in advance the weekly hours on each employee. Therefore, you would need a variable that can hold a value whenever such a value is entered.

 The Stack

A computer, in this case a computer with Intel-driven technology, is equipped with a memory area known as Random Access Memory or RAM that we will illustrate as a group of small boxes:

When the computers comes up (boots), part of this memory is filled with some values that primary applications, such as the operating system, need. Since the other parts of the memory are not used, they may be filled with garbage, that is, insignificant values you can't use because they mean nothing:

The memory (RAM) is huge enough to contain various values. The particularity of this memory is that it is temporary. In other words, it holds its values for a while and looses them when they are not needed anymore (an example is when the computer shuts down, the RAM is emptied). Normally, the operating system is in charge of the management of this whole memory, including when to put ("push") things in it and when to remove ("pop") things from it. This memory is also made available to you so that, while your application is "running", you can "put" things in it.

To better manage its memory, the computer sets aside an amount of memory space for programs like yours so that, when your application runs, it can use that memory to put values in it. This area of memory is called the Stack. As you may guess from its name, values are entered ("pushed") in it from a side, like entering a tunnel. Another particularity of this scenario is that the values are removed ("popped") from another side:

Keep in mind that the operating system removes any value when it (the OS) judges or finds out that the values is not used or needed anymore.

When your application runs, it will use (part of) this memory space as necessary. One way you can use it is to put values in the space as you judge it necessary.

 Variable Declaration

Imagine you are creating a program that will calculate the weekly salary of various employees. This would be done by multiplying the weekly hours by the hourly salary:

Weekly Salary = Weekly Hours * Hourly Salary

This means that you will likely need an amount of memory space to store a value for the weekly salary (a monetary value), another amount to store a value for the weekly hours (a regular number) and another to store a value for the hourly salary (another regular number). You also may want your program to display the name of the employee and to specify whether the employee is married or not. The name can be made of one or various words.

In order to store these values in the memory, you must tell the computer how much space each value will need. This is because the compiler cannot predict what your program will need. When specifying the amount of space, the compiler will reserve an amount of space for each value you specify but the compiler will not tell where the reserved memory is. To locate that memory, you must give it a name. The name is not stored as a value; it only allows you to be able to refer to the space memory that was reserved for your variable.

Reserving an area of memory is referred to as declaring a variable. There are strict rules you must follow when doing this. The general formula used to declare a variable is:

TypeOfVariable VariableName;

When you ask the compiler to reserve an amount of space memory for your variable, you must tell it how much memory the variable will need. This is because different values are meant to do different things. For example, while a number can be used to hold the salary of an employee, a word or a group of words is necessary to hold the name of an employee.

The second piece of information you must specify, as mentioned already, is a name that you will use to refer to the memory that was reserved for a particular variable. The names of variables follow the same rules we reviewed for namespaces.

 Overview of Data Types

 Variable Initialization

When you declare a variable, as mentioned already, the compiler reserves a space in memory for that variable. In most languages, that space is left empty until you put a value in it. In Managed C++, that space is filled with a 0 value. Initialization is a technique of putting a value into the space memory of a variable. We also state that variable is assigned a value. To control the behavior of your program, you can assign the desired value to a variable when you declare it. That is, you can initialize a variable when declaring it. There are two main techniques used to initialize a variable.

You can use the equal symbol (also called the assignment operator) to initialize a variable. To do that, after typing the name of the variable, type = followed by the desired value. The formula used would be:

TypeOfVariable VariableName = InitialValue;

Another technique of initializing a variable is by using parentheses. The syntax is:

TypeOfVariable VariableName(InitialValue);

 Introduction to Data Types

We have mentioned that the syntax of declaring a variable was:

TypeOfVariable VariableName;

The TypeOfVariable factor lets the compiler know the amount of memory that will be needed for the variable. This TypeOfVariable is commonly called the data type. As we will find out, there are various data types available in Managed C++.

If many different variables are using the same data type, you can declare them on the same line, separating two with a comma, except the last one that would end with a semi-colon. The formula to follow is:

DataType Variable1, Variable2, Variable3;
 Boolean Variables

A Boolean value is one can have only one of two values. Either it is true or it is false. It is also sometimes considered being either 0 or non-0 but Managed C++, unlike C++, makes a formal distinction between a Boolean value and a number.

To declare a Boolean variable, you can use the bool keyword. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
bool drinkingUnderAge;

return 0;
}

Alternatively, you can also declare a Boolean variable using the Boolean keyword. The Boolean data type is part of the System namespace. Here are two examples of declaring variables using the Boolean data type:

#using <mscorlib.dll>
using namespace System;

int main()
{
Boolean drinkingUnderAge;
System::Boolean TheFloorIsCoveredWithCarpet;

return 0;
}

To display the value of a Boolean variable, you can type its name in the parentheses of Write or WriteLine. After the variable has been declared, the compiler initializes it with a false value. This can be demonstrated in the following program:

#using <mscorlib.dll>
using namespace System;

int main()
{
Boolean drinkingUnderAge;

Console::WriteLine(drinkingUnderAge);
return 0;
}

This would produce:

False
Press any key to continue

You can initialize the Boolean variable to true or false when you declare it to make sure you know its initial value. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
Boolean drinkingUnderAge = true;

Console::WriteLine(drinkingUnderAge);
return 0;
}

At any time and when you judge it necessary, you can change the value of the Boolean variable by assigning it a true or false value. Here is an example:

 #using using namespace System; int main() { Boolean drinkingUnderAge = true; Console::WriteLine(drinkingUnderAge); drinkingUnderAge = false; Console::WriteLine(drinkingUnderAge); return 0; }

This would produce:
 True False Press any key to continue

 Integers

 Signed and Unsigned Numbers

An integer is a natural number typically used to count items. An integer is considered a "whole number" because it doesn't display a decimal fraction.

A number can be expressed as being positive or negative. When a number is written like 248, it is considered positive. Such a number is greater than 0. To specify that a number is negative, you must type - to its left. An example would be -248. When declaring a variable that would hold a number, you will have the option of specifying that the variable can hold a positive or a negative value.

A variable is referred to as signed when it can hold either a positive or a negative number. The positive sign can be set by either not typing any sign to its left, as in 248, or by adding + to its left, as in +248.

A variable is referred to as unsigned if it must hold only a positive number. If it is given a negative number, in the best case scenario, the compiler would not do anything. In the bad case scenario, the value would be unpredictable. With some compilers, the program would crash.

 Bytes

The most fundamental number in Managed C++ is represented by the Byte data type (this data type is not formally used in C++). A Byte is an unsigned number whose value ranges from 0 to 255. To declare such a variable, you can use the Byte keyword. The Byte data type is defined in the System namespace. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
Byte Age = 242;

Console::WriteLine(Age);

Console::WriteLine();
return 0;
}

This would produce:

242

Press any key to continue

If you want to use a small number but whose variable can hold either positive or negative values, you can declare it using the SByte data type. A variable declared with SByte can hold a value between -127 and 128, not more, not less. The SByte data type is defined in the System namespace. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
SByte Age = -36;

Console::WriteLine(Age);

Console::WriteLine();
return 0;
}

This would produce:

-36

Press any key to continue

 Short Variables

If you need to represent a number that is a little higher than the Byte can hold, you can declare it using the short keyword. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
short Age;

return 0;
}

A short variable can hold a natural number whose value ranges from -32768 to 32767. Based on this, it is important to note that a Byte value can fit in a short. Therefore, it is normal to declare as short a variable that would hold even small numbers such as people's ages.

When assigning a value to the variable, you can use a number in that range. If you assign a value out of that range, you would receive a warning and the number would be "truncated". That is, the number would be converted to the value of the other extreme. Consider the following program:

#using <mscorlib.dll>
using namespace System;

int main()
{
short Number = 32769;

Console::WriteLine(Number );

Console::WriteLine();
return 0;
}

This would produce the following warning:

Exercise.cpp(6) : warning C4309: 'initializing' : truncation of constant value

The program would produce:

-32767

Press any key to continue

If you want to enforce the idea that the variable is signed, you can type the signed keyword before short. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
signed short Number = -326;

Console::WriteLine(Number );

Console::WriteLine();
return 0;
}

If you want the variable to hold only positive numbers, you can type the unsigned keyword to the left of short and make sure you omit the signed keyword. When using the unsigned keyword, you can store numbers that range from 0 to 65535. If you assign either a negative number or a number higher than 65535, the number would be truncated. This time, the truncation is done differently but the result is not as intended. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
unsigned short Number = -326;

Console::WriteLine(Number );

Console::WriteLine();
return 0;
}

After a warning, this would produce:

65210

Press any key to continue

Besides the short keyword, to declare a variable for a relatively small number, you can use the Int16 data type. The Int16 data type is defined in the System namespace. Its variable can hold values in the same range as the short. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
System::Int16 Number = -326;

Console::WriteLine(Number );

Console::WriteLine();
return 0;
}

Because an Int16 variable can hold negative values, if you want to use only positive values, you can declare the variable using the UInt16 data type (The U stands for "unsigned"). The UInt16 data type is defined in the System namespace. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
System::UInt16 Number = 60326;

Console::WriteLine(Number );

Console::WriteLine();
return 0;
}

This would produce:

60326

Press any key to continue
 Integral Variables

In some cases you may need a variable that hold a number larger than the short or the Int16 can carry. To declare such a variable, you can use the int keyword. The int data type is used for a variable whose value can range from –2,147,483,648 to 2,147,484,647. Here is an example:

 #using using namespace System; int main() { int Number = 602; Console::WriteLine(Number); Console::WriteLine(); return 0; }

Compiled, the program would produce:

 602 Press any key to continue

It is important to note that, thanks to its range of values, an int variable can hold the same values as the Byte, the short, or the Int16. Therefore, it is perfectly normal and sometimes preferable to use int for a variable intended to hold natural numbers.

By default, an int declared variable can hold either positive or negative values. You can still enforced this by typing the signed keyword to the left of int:

#using <mscorlib.dll>
using namespace System;

int main()
{
signed int Number = 602;

Console::WriteLine(Number);

Console::WriteLine();
return 0;
}

If you want the variable to hold only positive numbers, you can type the unsigned keyword to its left and omit the signed. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
unsigned int Number = 46082;

Console::WriteLine(Number);

Console::WriteLine();
return 0;
}

Besides the int keyword, you can use the Int32 data type. An Int32 holds the same range of values as the int. The Int32 data type is defined in the System namespace. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
System::Int32 Number = 46802;

Console::WriteLine(Number);

Console::WriteLine();
return 0;
}

To specify that the variable must hold only positive numbers, besides unsigned int, you can use the UInt32 data type to declare the variable. The UInt32 data type is defined in the System namespace. Here is an example:

 #using using namespace System; int main() { UInt32 Number = 46082; Console::WriteLine(Number); Console::WriteLine(); return 0; }

 Long Integers

While the int and the Int32 data types can hold significantly large numbers, you may still need a variable that can hold very large numbers. Such a variable can be declared using the long data type. Such a variable can hold a number that ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Based on this, it is important to note that a long variable can hold a short, an int, an Int16 or an Int32 variable but, unlike the int and the Int32 that are more commonly used, the long is more appropriate if you know that the variable will really need to carry very very large numbers. Otherwise, the long can use significant memory.

Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
long Number = 46082;

Console::WriteLine(Number);

Console::WriteLine();
return 0;
}

This would produce:

46082

Press any key to continue

When declaring a variable as long, it can hold either positive or negative numbers. You can still enforce this by declaring the variable as signed long.

 Characters

 Symbolic Characters

A character is a symbol that displays on your screen. It can be a letter such as a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z. It can also be a letter from A to Z. It can also be a digit such as 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. It can also by a special characters such as ` ~ # \$ ! @ % ^ & * ( { [ ) } ] | \ : ; “ ‘ + - < _ ? > , / =. A character is really an integer whose value can range from -128 to 127.

To declare a character variable, you use the char keyword. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
char AlphaLetter;

Console::WriteLine();
return 0;
}

Since a char variable represents one symbol, to initialize it, enclose the initial value in single quotes. Here are examples:

#using <mscorlib.dll>
using namespace System;

int main()
{
char AlphaLetter = 'd';
char Pick('G');

Console::WriteLine();
return 0;
}

A character variable can also be declared with the signed char data type. This type of variable would be an integer whose value can range from –128 to +127.

 Unicode Characters

One of the limitations of the char data type is that it can fit only on a single character (limited to 8 bits). To support a wider range of characters, you can use the Char or the __wchar_t data types to declare a character variable. In fact, when using Visual C++ .Net, you should use either Char or __wchar_t whenever you need a character. The Char and the __wchar_t data types are defined in the System namespace. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
__wchar_t AlphaLetter = 'F';

Console::WriteLine(AlphaLetter);

Console::WriteLine();
return 0;
}

This would produce:

F

Press any key to continue

Based on their structures, Char and __wchar_t variable can accommodate letters in many other languages than Latin-based. When initializing a variable declared with Char or __wchar_t, to indicate that you are using a Unicode character, you can precede the quoted value with L. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
Char Letter = L'D';

Console::WriteLine(Letter);

Console::WriteLine();
return 0;
}

This would produce:

D

Press any key to continue

 The String: A List of Characters

A string is a group of characters considered as one unit, as opposed to a single character as we introduced above. Unlike some other languages such as (Object) Pascal or (Visual) Basic, C++ doesn't have a data type that can hold a group of characters as one entity (this is one of the limitations that Manage C++ solves completely). The alternative was to "create" and adapt a string data type in additional library. This problem was partially solved in a library called Standard Template Library (STL). Therefore, the STL provides the string data type. Since we will not study the STL in this e-book, we will not go into its details. We will only use its string type.

To declare a variable that can hold a string, you can use the string data type (the string is a class but we will consider it a data type for simplicity). The value of the string must be included in double-quotes. Here is an example:

The string data type is part of the std namespace and it is defined in the string library. When using the string data type, make sure you include the string library and use the std namespace. Because Managed C++ doesn't directly support STL but the included compiler does, to display the value of a string variable, you can use the cout extractor (you can also use Write or WriteLine but you would need to call the string::c_str() method; we haven't learned what a method is). Here is an example:

#using <mscorlib.dll>
#include <string>
#include <iostream>
using namespace std;
using namespace System;

int main()
{

cout << Course;

Console::WriteLine();
return 0;
}

This would produce:

Press any key to continue

 Decimal Numbers

 Floating-Point Variables

The integers we have used so far don't allow decimal values. C++ provides floating identifier values that would solve this problem. To declare a variable that involves a decimal value, you can use the float keyword. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
float Fraction = 12.35;

Console::WriteLine(Fraction);

Console::WriteLine();
return 0;
}

A float variable can hold a number that ranges from 3.4 x 10-38 to 3.4 x 1038. Besides float, you can also use the Single data type to declare a variable that holds a simple decimal value. The Single data type is defined in the System namespace.

 Double-Precision Variables

One of the limitations of the float data type is that it provides less precision than required sometimes (in fact, the Microsoft C++ compiler, including the one used in Visual C++ 6, always displays a warning when using the float keyword to declare a variable). The alternative is to use the double keyword or the Double data type to declare a variable that would hold decimal numbers. The Double data type is defined in the System namespace.

A double-precision variable declared with double or Double can hold a decimal or fractional number that ranges from 1.7 x 10-308 to 1.7 x 10308. It is used for numbers that and/or are very large.

 #using using namespace System; int main() { System::Double Fraction = 12.35; Console::WriteLine(Fraction); Console::WriteLine(); return 0; }

This would produce:

12.35

Press any key to continue
 Techniques of Using Variables

 Introduction

C++ allows you to create new data types that are not directly shipped with the compiler. A new data type can be a simple adaptation of an existing one or it can be a group of data types put together to lead to a new type. The technique used to get a new type depends first on what is available, then on your intentions.

 Preprocessors: #define

The #define, called a directive, is used to direct the compiler to create or perform a (small) action. This action is called a macro. For example, you can ask the compiler to use "Rio de Janeiro" whenever it sees RDJ. To do that you can write

#define RDJ "Rio de Janeiro"

If you use the word RDJ in your program, the compiler would replace it with the defined name. You can also use the #define directive to create words that would be replaced with numeric values. Here is an example:

#using <mscorlib.dll>
#include <iostream>
using namespace std;

#define RDJ "Rio de Janeiro"

int main()
{
cout << "City: " << RDJ << "\n";

return 0;
}

This would produce:

City: Rio de Janeiro
Press any key to continue

 Enumerations

An enumeration provides a technique of setting a list of numbers where each item of the list is ranked and has a specific name. For example, imagine you are writing a list of types of members of a public library and the list is made of Teen, Adult, and Senior. Instead of considering each category as a word, you can make it to be a number.

To create an enumerator, you can use the enum keyword, followed by the name of the enumerator, followed by a name for each item of the list. The name of the enumerator and the name of each item of the list follows the rules we reviewed already. The formula of creating an enumeration is:

enum Series_Name {Item1, Item2, Item_n};

Here is an example:

 #using using namespace System; int main() { enum MembershipType { Teen, Adult, Senior }; return 0; }

After creating an enumerator, and before using any of the values in the list, each item in the list is assigned a constant number. The items are counted starting at 0, then 1, etc. By default, the first item in the list is assigned the number 0, the second is 1, etc. You can specify or change the numbers to your liking when you create the enumerator but once the enumerator has been created, whether you specified these numbers or not, they cannot be changed.

In our list above, the Teen member would have a value of 0. The Adult member would have a value of 1. The Senior would have a value of 2. This is demonstrated in the following program:

#using <mscorlib.dll>
using namespace System;

int main()
{
enum MembershipType { Teen, Adult, Senior };

Console::WriteLine(Teen);
Console::WriteLine(Senior);

Console::WriteLine();
return 0;
}

This would produce:

0
1
2

Press any key to continue

As mentioned already, you can change the numbers assigned to the members of the enumerator when you create it. To make the list start at a specific number, assign the starting value to the first item in the list. Here is an example:

 #using using namespace System; int main() { enum MembershipType { Teen = 4, Adult, Senior }; Console::WriteLine(Teen); Console::WriteLine(Adult); Console::WriteLine(Senior); Console::WriteLine(); return 0; }

This would produce:

4
5
6

Press any key to continue

Notice that, this time, the Teen member has a value of 4, the Adult member has a value of 5, and the Senior is 6. When creating the array, you can assign any value of your choice to any item in the list, or you can set different ranges of values to various items. You can create a list like this:

 #using using namespace System; int main() { enum MembershipType { Teen, Adult, Senior = 12 }; Console::WriteLine(Teen); Console::WriteLine(Adult); Console::WriteLine(Senior); Console::WriteLine(); return 0; }

This would produce:

0
1
12

Press any key to continue

As mentioned already, you can assign any value to any member of the array. You can event assign the same number to different members of the array. Here is an example:

 #using using namespace System; int main() { enum MembershipType { Teen = 26, Adult, Senior = 12, Unknown = 5 }; Console::WriteLine(Teen); Console::WriteLine(Adult); Console::WriteLine(Senior); Console::WriteLine(Unknown); Console::WriteLine(); return 0; }

This would produce:

26
27
12
5

Press any key to continue

An enumerator in reality is a way to create an integer data type whose value would be represented by an easily recognizable number from its name instead of a number that could mean anything to anybody. For example, its easier to recognize a word such as FullTime instead of 4 even if both have been internally set. Based on this, once you have created an enumerator, the name you give to the list, such as MembershipType, becomes a data type of its own, and it can be used to declare a variable. Therefore, a variable of the enumerated type would be declared as:

Series_Name VariableName;

Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
enum EmploymentStatus { FullTime, PartTime, Contractor, Intern };

EmploymentStatus Status;

Console::WriteLine(Status);

Console::WriteLine();
return 0;
}

When you declare a variable using an enumerator, the variable is initialized to the value of the first member of the enumerator. Consider the following program:

#using <mscorlib.dll>
using namespace System;

int main()
{
enum EmploymentStatus { FullTime, PartTime, Contractor, Intern };

EmploymentStatus Status;

Console::WriteLine(Status);

Console::WriteLine();
return 0;
}

This would produce:

0

Press any key to continue

As you may realize if you execute the above program, the compiler doesn't like when a variable declared from an enumerator is not initialized. Therefore, when you declare such a variable, you should initialize. This can be done by assigning the name of the desired member to the variable. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
enum EmploymentStatus { FullTime = 2, PartTime, Contractor = 16, Intern };

EmploymentStatus Status = PartTime;

Console::WriteLine(Status);

Console::WriteLine();
return 0;
}

This would produce:

3

Press any key to continue

As done with the other variables, you can declare more than one variable of an enumerator type. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
enum EmploymentStatus { FullTime = 2, PartTime, Contractor = 16, Intern };

EmploymentStatus Seasonal    = Contractor,
Replacement = PartTime;

Console::WriteLine(Replacement);
Console::WriteLine(Seasonal);

Console::WriteLine();
return 0;
}

This would produce:

3
16

Press any key to continue

Instead of declaring them after the list has been created, you can declare the variables of the enumerator type on the right side of the list but before the closing semi-colon. Here is an example:

 #using using namespace System; int main() { enum EmploymentStatus { FullTime=2, PartTime,Contractor=16, Intern } Seasonal, Replacement; Console::WriteLine(); return 0; }

You can also initialize he variable(s) when declaring it(them). Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
enum EmploymentStatus { FullTime = 2,
PartTime,
Contractor=16, Intern }
Seasonal = PartTime,
Replacement = Intern;

Console::WriteLine(Replacement);
Console::WriteLine(Seasonal);

Console::WriteLine();
return 0;
}
 References

A reference is a variable name that is a duplicate of an existing variable. It provides a technique of creating more than one name to designate the same variable. The syntax of creating or declaring a reference is:

DataType &ReferenceName = VariableName;

To declare a reference, type the variable’s name preceded by the same type as the variable it is referring to. Between the data type and the reference name, type the ampersand operator “&”. To specify what variable the reference is addressed to, use the assignment operator “=” followed by the name of the variable. The referred to variable must exist already. You cannot declare a reference as:

int &Mine;

The compiler wants to know what variable you are referring to. Here is an example:

 #using using namespace System; int main() { int Number = 228; int &Nbr = Number; Console::WriteLine(); return 0; }

The ampersand operator between the data type and the reference can assume one of three positions as follows:

int& Nbr;
int & Nbr;
int &Nbr;

As long as the & symbol is between a valid data type and a variable name, the compiler knows that the variable name (in this case Nbr) is a reference.

Once a reference has been initialized, it holds the same value as the variable it is pointing to. You can then display the value of the variable using either of both:

 #using #include using namespace std; using namespace System; int main() { int Number = 228; int &Nbr = Number; cout << "Number: "; Console::WriteLine(Number); cout << "Its reference: "; Console::WriteLine(Nbr); Console::WriteLine(); return 0; }

This would produce:

Number:        228
Its reference: 228

Press any key to continue

If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:

 #using #include using namespace std; using namespace System; int main() { int Number = 228; int &Nbr = Number; cout << "Number: "; Console::WriteLine(Number); cout << "Its reference: "; Console::WriteLine(Nbr); Number = -15008; cout << "\nNumber: "; Console::WriteLine(Number); cout << "Its reference: "; Console::WriteLine(Nbr); Number = 28114; cout << "\nNumber: "; Console::WriteLine(Number); cout << "Its reference: "; Console::WriteLine(Nbr); Console::WriteLine(); return 0; }

This would produce:

Number:        228
Its reference: 228

Number:        -15008
Its reference: -15008

Number:        28114
Its reference: 28114

Press any key to continue

It is very important to remember the relationship that a variable in the stack has with its value: A variable in the stack contains its own value. Whenever you access this variable, it gives you copy of its value and retains the original. Once you have that value, you can do what you want with it and this would not have any impact on the variable itself or its value. For example, if you assign such a value to another variable, that other variable receives its own copy. Let's illustrate with the following program:

// This is the main project file for VC++ application project
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
int Number1 = 255;
int Number2 = Number1;

Console::WriteLine(Number1);
Console::WriteLine(Number2);

Console::WriteLine();
return 0;
}

This would produce:

255
255

Press any key to continue

Notice that when the value of the first variable has been assigned to the second variable both variables hold the same value. With another assignment, you can change the value of the second variable and the first would keep its value:

// This is the main project file for VC++ application project
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>

using namespace std;
using namespace System;

int _tmain()
{
int Number1 = 255;
int Number2 = Number1;

Console::WriteLine(Number1);
Console::WriteLine(Number2);
Console::WriteLine();

Number2 = -48;

Console::WriteLine(Number1);
Console::WriteLine(Number2);
Console::WriteLine();
return 0;
}

This would produce:

255
255

255
-48

Press any key to continue

This comparison is important because its sets apart the references as we saw above. This will be even more important with pointers in the next lesson.

 The typedef Type Definition

The data types we have used so far may have names we are not familiar with. C++ allows to customize the name of a data type to a name you are more familiar with. You would not (and are not allowed to) create a new data type, you would only "redefine" the name of an existing data type.

To customize the name of a data type, you can use the typedef keyword. The formula used is:

typedef KnownDataType NewName;

The typedef keyword is required to let the compiler know that you are creating a new data type. The data type must be one that exists already, such as those we have reviewed so far. It could be an int, an unsigned int, an Int32, a char, a double, etc. An example of using a typedef is:

#using <mscorlib.dll>
#include <iostream>

using namespace std;
using namespace System;

int main()
{
typedef unsigned int PositiveNumber;

Console::WriteLine();
return 0;
}

In this case, PositiveNumber is just a new name for an unsigned int. It can be used as a new data type exactly as if you were using an unsigned int. Here are examples:

 #using #include #include using namespace std; using namespace System; int main() { typedef unsigned int PositiveNumber; typedef string EmploymentStatus; typedef double Salary; PositiveNumber Gender = 1; EmploymentStatus Status = "Full Time"; Salary WeeklySalary = 1450; cout << "Gender: "; Console::WriteLine(Gender); cout << "Status: "; cout << Status; cout << "\nSalary: \$"; Console::WriteLine(WeeklySalary); Console::WriteLine(); return 0; }

This would produce:

 Gender: 1 Status: Full Time Salary: \$1450 Press any key to continue

 Constants

 Constant Values

A constant is a value that does not change. There are various categories of constants you will be using in your programming life: those that are mathematically defined (such as numbers) and those that are defined by, and are part of, the Managed C++ language. To make their management easier, these constant values have been categorized and defined in particular libraries.

The algebraic numbers you have been using all the time are constants because they never change. Examples of constant numbers are 12, 0, 1505, or 88146. Therefore, any number you can think of is a constant.

Every letter of the alphabet is a constant and is always the same. Examples of constant letters are d, n, c.

Some characters on your keyboard represent symbols that are neither letters nor digits. These are constants too. Examples are #, &, |, !.

There are two main techniques you use to display a constant value in Managed C++. To simply display it using Write or WriteLine, you can type its value in the parentheses. Here is an example:

#using <mscorlib.dll>

using namespace System;

int main()
{
Console::WriteLine(2850);

Console::WriteLine();
return 0;
}

This would produce:

2850
Press any key to continue

You can also define it first using an appropriate name, and then using that name to display the constant. Here is an example:

#using <mscorlib.dll>

using namespace System;

int main()
{
typedef unsigned int Positive;

Positive Number = 1450;
Console::WriteLine(Number);

Console::WriteLine();
return 0;
}
 Custom Constants

You can create your own constant that represents anything you want. The safest technique of using a constant is to give it a name. This allows you to manage it from one standpoint. For example, if you plan to use a number such as 3.14 that represents PI, you can simply use the constant 3.14. Imagine you want to use 3.14 in various sections of the program. If you decide to change the number from 3.14 to 3.14159 or another value, you would have to find every mention of 3.14; this can be cumbersome and considered bad programming. The alternative is to declare a variable and assign it the desired value. That new and defined value is called a constant.

To create a constant, you use the const keyword. The simplest way you can do this is to type the const keyword followed by a name, followed by =, followed by the desired value, and terminated by a semi colon. Here is an example:

const NumberOfDoors = 4;

After creating such a constant, you can display its value using Write or WriteLine. You can also involve such a constant in an operation.

When creating a constant as done above, the compiler assumes that the constant is a natural number. If you initialize it to a value that is not an integer, the compiler would try to convert it into an integer but you would receive a warning. Consider the following example:

#using <mscorlib.dll>
using namespace System;

int main()
{
const NumberOfDoors = 4.16;

Console::Write("Number of doors = ");
Console::WriteLine(NumberOfDoors);
return 0;
}

This would produce:

Number of doors = 4
Press any key to continue

The safest way to create a constant is to specify the type of data of that constant. To do this, you enter the data type between the const keyword and the name of the constant. Here are examples:

const double NumberOfValues    = 125.558;
const long double Population   = 258994;
const unsigned short int Alley = 88;

If you already know (and have included) a constant, you can initialize your new constant with it. Here is an example:

#using <mscorlib.dll>
using namespace System;

int main()
{
const double NumberOfValues = 125.558;
const unsigned short int Alley = 88;

const double Root = NumberOfValues;

Console::WriteLine();
return 0;
}

 Using #define

The C language provides a preprocessor used to create macros. A macro is an action you want the compiler to perform for your program. The particularity of macros, or most macros, is that the compiler counts on you to know what you are doing. Many of such macros are created using the #define preprocessor.

Based on this concept of macros, you can create a constant. The formula of creating a constant using the define keyword is:

#define ConstantName ConstantValue

The # symbol and the define keyword are required; they inform the compiler that the following name represents a constant.

The ConstantName represents a valid name for the desired constant; the name follows the same rules we learned for defining names. To distinguish the constant from other names of variables, it is sometimes a good idea to write it in uppercase, although it is perfectly normal to have it in lowercase or any case combination you desire.

The ConstantValue can be a character, an integer, a floating-point value, or an expression. If the constant value is an integer or a floating-point value, you can type it. If the value is a character, include it between single-quotes. If the constant value is a string, include it between double-quotes. The definition of the constant does not end with a semi-colon.

Examples of declaring constants are:

 #define AGE 12 // AGE represents the constant integer 12 #define ANSWER ‘y’ #define MAXSTUDENTS 35 #define And "&&" #define PI 3.14159 // PI represents 3.14159 #define Country = “New Zealand”;

As you can see, there is no precision as to what type of constant you are creating when using #define. The truth is that #define doesn't create a constant. It is simply telling the compiler that the word after #define will be used to represent whatever follows that ConstantName. This means that, in reality, what follows ConstantName can be anything; it can even be an expression. here is an expression:

#using <mscorlib.dll>
#include <iostream>

using namespace std;
using namespace System;

#define Welcome cout << "Welcome to the wonderful world of Managed C++!\n"
#define Print Console::WriteLine()

int main()
{
Welcome;
Print;
return 0;
}

This would produce:

Welcome to the wonderful world of Managed C++!

Press any key to continue

The #define technique was implemented in the C language and C++, as a child of C, simply inherited it from its parent. The #define routine is still supported and you will encounter it in many documents.