Values and their Types
Values and their Types
Variables
Introduction
When interacting with the computer, a user enters values, changes them, retrieves them, etc. You can monitor most of these operations as they relate to your application. To start, you can display values to the user using the Write and the WriteLine methods of the Console class of the System namespace. A variable is a value that you want to use in your program without primarily knowing how much exactly that value will be when the program runs. |
The Stack |
A computer is equipped with a memory area known as Random Access Memory or RAM that we will illustrate as a group of small boxes:
When a computer 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 (OS) removes any value when it (the OS) judges or finds out that the value(s) is(are) 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 necessary.
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). |
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, in the stack memory. 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 rules you must follow when doing this. The general formula used to declare a variable in C is:
TypeOfVariable VariableName;
When you ask the compiler to reserve an amount of memory space 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.
If you want to declare more than one variable of the same type, you can declare each with the type, its name, and its semi-colon. The formula to follow would be:
TypeOfVariable Variable1; TypeOfVariable Variable2; TypeOfVariable Variable_n;
An alternative is to use one data type followed by the names of variables that would share this type. The names of variables must be separated by commas. The formula to follow would be:
TypeOfVariable Variable1, Variable2, Variable_n;
If you want to declare different variables that use different data types, you can declare each with the type, its name, and its semi-colon, on the same line. The formula to follow would be:
TypeOfVariable1 Variable1; TypeOfVariable2 Variable2; TypeOfVariable3 Variable3;
A better alternative is to declare each variable on its own line. This makes the program easier to read. The formula to follow would be:
TypeOfVariable1 Variable1; TypeOfVariable2 Variable2; TypeOfVariable3 Variable3;
When using the various necessary variables in your programs, you will need to identify each one of them. A variable is primarily recognized by its name. C++ provides rules for naming items in your program. The name of a variable:
|
A name can consist of one word such as country. A name could also be a combination of more than one word, such as firstname or dateofbirth.
The C++ and the C++/CLI languages have a list of words reserved for its own use and you must not use any of these words to name your objects or functions. The reserved words are:
C and C++ Reserved Words | ||||
abstract | auto | bool | break | case |
catch | char | class | const | const_cast |
continue | default | delegate | delete | do |
double | dynamic_cast | each | else | enum |
explicit | extern | event | false | finally |
float | for | friend | gcnew | generic |
goto | if | in | inline | int |
internal | initonly | interface | literal | long |
mutable | namespace | new (pointer) | new (abstract) | nullptr |
operator | override | private | property | protected |
public | ref | register | reinterpret_cast | return |
sealed | signed | sizeof | short | static |
static_cast | struct | switch | template | this |
true | try | typedef | typeid | throw |
typename | union | unsigned | using(namespace) | using(inheritance) |
value | virtual | void | volatile | wchar_t |
while | where |
Avoid starting the name of a variable with two underscores; sometimes, the compiler would think that you are trying to use one of the words reserved for the compiler.
C++ is case-sensitive; this means that CASE, Case, case, and Case are four completely different words. To make your programming experience easier and personal, you can add your own rules to those above. Some (most) companies also adopt a naming convention throughout their documentation.
Throughout this book, a name will:
When you declare a variable, as mentioned already, the compiler reserves a space in memory for that variable in the stack. In most languages, that space is left empty until you put a value in it. 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 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;
using namespace System; int main() { Console::WriteLine("=//= Altair Realty =//="); Console::WriteLine("-=- Properties Inventory -=-"); return 0; }
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.
The most fundamental number in C++/CLI 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 namespace System; int main() { Byte Age = 242; Console::WriteLine(Age); 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 namespace System; int main() { SByte Age = 24; Console::WriteLine(Age); return 0; }
This would produce:
24 Press any key to continue
Practical Learning: Declaring a Byte Variable |
using namespace System; int main() { Byte stories = 2; Console::WriteLine("=//= Altair Realty =//="); Console::WriteLine("-=- Properties Inventory -=-"); Console::WriteLine("Property:"); Console::Write("Stories: "); Console::WriteLine(stories); return 0; }
=//= Altair Realty =//= -=- Properties Inventory -=- Property: Stories: 2 Press any key to continue . . .
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 namespace System; int main() { short Pages = 424; Console::WriteLine(Pages); 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 namespace System; int main() { short Number = 32769; Console::WriteLine(Number ); Console::WriteLine(); return 0; }
This would produce the following warning:
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 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 namespace System; int main() { unsigned short Number = -326; Console::WriteLine(Number ); 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 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 namespace System; int main() { System::UInt16 Number = 60326; Console::WriteLine(Number ); Console::WriteLine(); return 0; }
This would produce:
60326 Press any key to continue
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 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, based on 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 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 namespace System; int main() { unsigned int Number = 46082; Console::WriteLine(Number); 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 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 namespace System; int main() { UInt32 Number = 46082; Console::WriteLine(Number); return 0; } |
Practical Learning: Declaring Unsigned Variables |
using namespace System; int main() { Byte stories = 2; unsigned bedrooms = 5; unsigned yearBuilt = 1962; Console::WriteLine("=//= Altair Realty =//="); Console::WriteLine("-=- Properties Inventory -=-"); Console::WriteLine("Property:"); Console::Write("Stories: "); Console::WriteLine(stories); Console::Write("Bedrooms: "); Console::WriteLine(bedrooms); Console::Write("Year Built: "); Console::WriteLine(yearBuilt); return 0; }
=//= Altair Realty =//= -=- Properties Inventory -=- Property: Stories: 2 Bedrooms: 5
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 large numbers. Otherwise, the long can use significant memory.
Here is an example:
using namespace System; int main() { long Number = 46082; Console::WriteLine(Number); 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.
Practical Learning: Declaring Long Integers |
using namespace System; int main() { long propertyNumber = 490724; Byte stories = 2; unsigned bedrooms = 5; unsigned yearBuilt = 1962; Console::WriteLine("=//= Altair Realty =//="); Console::WriteLine("-=- Properties Inventory -=-"); Console::Write("Property #: "); Console::WriteLine(propertyNumber); Console::Write("Stories: "); Console::WriteLine(stories); Console::Write("Bedrooms: "); Console::WriteLine(bedrooms); Console::Write("Year Built: "); Console::WriteLine(yearBuilt); return 0; }
=//= Altair Realty =//= -=- Properties Inventory -=- Property #: 490724 Stories: 2 Bedrooms: 5 Year Built: 1962 Press any key to continue . . .
Initializing an Integral Variable |
After declaring an integer variable, you can initialize it with an appropriate value. As far as the value is concerned, you have two main alternatives. You can initialize an integral variable with a decimal value as we have done so far. Alternatively, you can initialize an integral variable with a hexadecimal value.
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 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 namespace System; int main() { char AlphaLetter = 'd'; char Pick('G'); 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.
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, 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 namespace System; int main() { __wchar_t AlphaLetter = 'F'; Console::WriteLine(AlphaLetter); 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 namespace System; int main() { Char Letter = L'D'; Console::WriteLine(Letter); return 0; }
This would produce:
D Press any key to continue
Practical Learning: Using Character Variables |
using namespace System; int main() { long propertyNumber = 490724; __wchar_t propertyType = 'S'; Byte stories = 2; unsigned bedrooms = 5; unsigned yearBuilt = 1962; Console::WriteLine("=//= Altair Realty =//="); Console::WriteLine("-=- Properties Inventory -=-"); Console::Write("Property #: "); Console::WriteLine(propertyNumber); Console::Write("Property Type: "); Console::WriteLine(propertyType); Console::Write("Stories: "); Console::WriteLine(stories); Console::Write("Bedrooms: "); Console::WriteLine(bedrooms); Console::Write("Year Built: "); Console::WriteLine(yearBuilt); return 0; }
=//= Altair Realty =//= -=- Properties Inventory -=- Property #: 490724 Property Type: S Stories: 2 Bedrooms: 5 Year Built: 1962 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. 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.
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:
string Course = "Business Mathematics";
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. To display the value of a string variable, you can use the cout extractor. Here is an example:
#include <string> #include <iostream> using namespace std; using namespace System; int main() { string Course = "Business Mathematics"; cout << Course; Console::WriteLine(); return 0; }
This would produce:
Business Mathematics Press any key to continue
Decimal Numbers |
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 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, or instead of, float, you can 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.
Practical Learning: Using a Single-Precision Variables |
using namespace System; int main() { long propertyNumber = 490724; __wchar_t propertyType = 'S'; Byte stories = 2; unsigned bedrooms = 5; float bathrooms = 3.5; unsigned yearBuilt = 1962; Console::WriteLine("=//= Altair Realty =//="); Console::WriteLine("-=- Properties Inventory -=-"); Console::Write("Property #: "); Console::WriteLine(propertyNumber); Console::Write("Property Type: "); Console::WriteLine(propertyType); Console::Write("Stories: "); Console::WriteLine(stories); Console::Write("Bedrooms: "); Console::WriteLine(bedrooms); Console::Write("Bathrooms: "); Console::WriteLine(bathrooms); Console::Write("Year Built: "); Console::WriteLine(yearBuilt); return 0; }
=//= Altair Realty =//= -=- Properties Inventory -=- Property #: 490724 Property Type: S Stories: 2 Bedrooms: 5 Bathrooms: 3.5 Year Built: 1962 Press any key to continue . . .
One of the limitations of the float data type is that it provides less precision than required sometimes (in fact, the Microsoft C++ compiler, always displays a warning when you use the float data type 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 namespace System; int main() { System::Double Fraction = 12.35; Console::WriteLine(Fraction); return 0; }
This would produce:
12.35 Press any key to continue
Practical Learning: Using a Single-Precision Variables |
using namespace System; int main() { long propertyNumber = 490724; __wchar_t propertyType = 'S'; Byte stories = 2; unsigned bedrooms = 5; float bathrooms = 3.5; unsigned yearBuilt = 1962; double marketValue = 652540; Console::WriteLine("=//= Altair Realty =//="); Console::WriteLine("-=- Properties Inventory -=-"); Console::Write("Property #: "); Console::WriteLine(propertyNumber); Console::Write("Property Type: "); Console::WriteLine(propertyType); Console::Write("Stories: "); Console::WriteLine(stories); Console::Write("Bedrooms: "); Console::WriteLine(bedrooms); Console::Write("Bathrooms: "); Console::WriteLine(bathrooms); Console::Write("Year Built: "); Console::WriteLine(yearBuilt); Console::Write("Market Value: "); Console::WriteLine(marketValue); return 0; }
=//= Altair Realty =//= -=- Properties Inventory -=- Property #: 490724 Property Type: S Stories: 2 Bedrooms: 5 Bathrooms: 3.5 Year Built: 1962 Market Value: 652540 Press any key to continue . . .
Initializing a Double-Precision Variable |
You may have found out that when you declare and initialize a float or Single variable, the compiler generates a warning. Consider the following example:
using namespace System; int main() { float Fraction = 12.35; Console::WriteLine(Fraction); Console::WriteLine(); return 0; }
When compiled, you would get the following warning:
.\Exercise.cpp(5) : warning C4305: 'initializing' : truncation from 'double' to 'float'
Although the program would compile fine. By default, when the compiler sees a value such as 12.35, for the sake of precision, it tends to store it as a double value. If you really want the variable to be treated as a float or Single, add the f or F to its right. Here is an example:
using namespace System; int main() { float Fraction = 12.35f; Console::WriteLine(Fraction); Console::WriteLine(); return 0; }
This time, the compiler will not generate a warning. Remember that you can use f (lowercase) or F (uppercase).
Variable Reference |
The data types we have used so far may have names we are not familiar with. C++ allows you 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 namespace System; int main() { typedef unsigned int PositiveNumber; 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 namespace System; int main() { typedef unsigned int PositiveNumber; typedef double Salary; PositiveNumber Gender = 1; Salary WeeklySalary = 1450.88; Console::Write("Gender: "); Console::WriteLine(Gender); Console::Write("Salary: "); Console::WriteLine(WeeklySalary); return 0; }
This would produce:
Gender: 1 Salary: 1450.88 Press any key to continue . . .
A reference is a variable 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 variables 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 namespace System; int main() { int Number = 228; int &Nbr = Number; Console::WriteLine(Number); Console::WriteLine(Nbr); 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:
#include <iostream> 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:
#include <iostream> 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:
#include <iostream> using namespace std; using namespace System; int main() { // TODO: Please replace the sample code below with your own. 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:
#include <iostream> using namespace std; using namespace System; int main() { // TODO: Please replace the sample code below with your own. 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.
A Tracking Reference |
If you create a C++ reference as done above, the variable is stored in the stack. When the program ends, the compiler reclaims the memory the variable was using. The C++/CLI language provides another way to declare such a reference. In this case, the CLR garbage collector would be able to reclaim the memory that the variable was using. This type of variable is called a tracking reference.
To create a tracking reference, use the percent operator "%" instead of the ampersand. Here is an example:
int main() { int % PropertyValue; return 0; }
Like a native reference, in order to use a tracking reference, you must initialize it with a variable that has been declared and initialized appropriately. Here is an example:
using namespace System; int main() { double Value = 468550; double % PropertyValue = Value; Console::Write("Property Value = $"); Console::WriteLine(Value); Console::Write("Property Value = $"); Console::WriteLine(PropertyValue); return 0; }
After creating a tracking reference, if you change the value of the variable, the value of the tracking reference would be changed also. If you update the value of the tracking reference, the value of the variable would be updated also.
|
|||
Previous | Copyright © 2006-2025, FunctionX | Monday 14 October 2024, 10:12 | Next |
|