WORKING WITH VARIABLES


Constants are ideal for storing data that you do not want to change during program execution. However, you will most often need to store data that will change as your application runs. Variables are perfect for storing your data in these situations.

A variable is essentially a container for information. The variable's name is how Visual C++ keeps track of which data belongs to what part of your application.

Hint 

A variable stores data that might change during program execution.

Variables give your Visual C++ applications the ability to process all kinds of data. For example, in previous chapter game projects, you saw how applications used text boxes to collect player input. This input was then stored in variables and later processed.

There are two steps to working with variables:

  • Variable declaration. This involves the naming of a variable and the identification of the type of data that it will store.

  • Variable assignment. This is the process of assigning a value to a variable.

Declaring Variables

To declare a variable, you must think of a name and the type of data you want to store. The name represents a location in memory that your program will use automatically to hold whatever you want to store.

Hint 

The name of a variable is also called its identifier. That word applies to anything you name, including functions or classes. If your compiler ever gives you a message about an identifier, it's likely talking about something you created.

Visual C++ allows you to save space by declaring multiple variables of the same data type on a single line, as demonstrated next. If, for instance, you want to declare a variable that holds the maximum amount of text that a user should be allowed to enter into a text box, you might use this:

 Int16 intCounter; Single sngHighestTemperature; Double dblEscapeVelocity; 

These variables are ready to be assigned values. If you want to save space, you can declare variables of the same type on the same line. To do so, you declare the type and separate the variables names by a comma.

 Int16 intCurrentTime, intBestTime, intWorstTime; 

Defining Variables

When you declare a variable, you tell Visual C++ that you plan to use it elsewhere. But until you give the variable a value, it is said to be undefined. Defining a variable is the process of giving a variable its value.

Defining a variable is important because, until you do so, it has a random value in memory. Each time you run your application, the value might be different. Not until you tell Visual C++ to give your variable a value can you safely know what its contents will be should you refer to it later.

The syntax for defining a variable is exactly like declaring one, except that you follow the variable name by an equal sign and place a value after it. This causes your variable to take on whatever value that comes after the equal sign when your application runs. For instance, this example defines a variable:

 Int16 intCounter = 0; 

This statement, which you might use in your own code to keep track of certain items, defines a variable with the name of intCounter and sets its value to 0.

Trick 

It's often a good idea to initialize your variable as soon as you declare it.

Assigning Data to Variables

You can choose to declare a variable but not assign a value to it. This leaves you free to wait until the right moment in code to use the variable as you want. When it is time to use this variable, your application is free to assign a value to it. You can assign the contents of a value you type into the code or another variable.

 Int16 intIntCurrentAge; Int16 intOldestAge; intOldestAge = 100; intIntCurrentAge = intOldestAge; 

If you don't assign a value to your variables when you first declare, the value they hold is some random value.

To save space, you can combine variable declaration and assignment into one statement, as demonstrated here:

 Int16 intCurrentAge = 100; 

You can even declare and assign values to multiple variables in the same statement, as demonstrated next:

 Int16 intMinimumAge = 10, intMaximumAge = 120; 

Defining Local Variables

Local variables can be referenced only within the block or function where they are defined. Therefore, they are not accessible to other parts of a Visual C++ application.

Hint 

A block is a collection of statements that are processed as a unit. Blocks in Visual C++ begin with an opening curly brace ({) and end with a closing brace (}).

For example, the following statements demonstrate how to declare and assign data to a local variable name blnGameOver within a block:

 if( intCounter > 10 ) {   Boolean blnGameOver;   blnGameOver = false; } 

Because the blnGameOver variable is defined within a block, it cannot be referenced from anywhere outside the block. Similarly, the following example demonstrates how to declare and assign data to a local variable named strMessage within a procedure:

 private: System::Void button1_Click(System::Object^ sender, System::EventArgs^  e) {   String^ strName = gcnew String("");   strName = "Smith";   MessageBox::Show( strName ); } 

Local variables exist only while the block or procedure that declares them is executing. When the block or procedure ends, Visual C++ destroys any local variables. This process frees up memory that the variable used. Thus, using local variables can help reduce the overall amount of memory used by your application when compared to static variables, which have a longer lifetime.

Defining Static Variables

A static variable is one that is declared at the block or function level using the static keyword. Static variables can be referenced only within the block or procedure where they are defined; therefore, other parts of a Visual C++ application cannot access them. However, unlike local variables, a static variable continues to exist after the block or procedure that contains it has finished executing. In fact, a static variable exists as long as your application runs. The following example demonstrates how to use a static variable:

 private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {   static Int16 intCounter = 0;   intCounter += 1; } 

One good use for static variables is to create a procedure that behaves differently based on the number of times it has been executed. You can accomplish this by declaring a static variable with a data type of Int16, incrementing its value by 1 each time the procedure executes, and adding programming logic for the procedure to behave differently when the value of the static variable reaches a certain number. You will see an example of this in this chapter's game program.

Defining Variable Scope

As discussed earlier, every variable has a scope that defines whether a given block of code can see and use it. Because blocks of code are more or less defined by a set of opening and closing braces in Visual C++, braces set the limits of any variable's scope. If a variable is declared within a set of braces, it is invisible outside those braces. This feature of the C++ language allows you to create and use variables right in the middle of your program without having to worry that operations will contaminate them later on.

This rule of visibility works only one way, though. Variables that are declared outside of a block of code can be "seen" and used by the code within an inner set of braces. This works to your advantage because you often need to have some code that is within braces use a variable that was declared well above (and hence outside of) where the changes need to take place.

Rules for Naming Variables

You need to be aware of a few rules that govern the naming of variables. Failure to follow these rules, listed next, results in an error.

  • Variable names must begin with either an alphabetic character or the underscore character.

  • Variable names cannot include spaces.

  • Variable names cannot be reserved words.

Variable names must be unique. Names are case sensitive, meaning that variables such as userName, UserName, USERNAME, and username are treated as separate variables. So, in general, no two variables can have the same name. The exception to this involves the variable's scope, or visibility to other parts of your program. (See the previous section in this chapter titled "Defining Variable Scope" for more information.) Despite the flexibility that you have in naming your variable, it is best if you are consistent and avoid similarly spelled variables. Doing otherwise can make it difficult to understand your code and find and fix problems later on.

Another useful guideline involves giving your variables names that reflect their purpose. Like a constant, a good variable tells you at a glance why it is in the code. Using textCounter might be preferable to textCntr for that reason. The more your variable names describe their function, the more logical and organized your code will appear.

Above all, you should strive to avoid ambiguity. If you have a program that deals with containers and counters, cntr is likely a bad idea for a variable's name. So, too, is temp if you're dealing both with temporary variables and temperatures.

image from book
IN THE REAL WORLD

You have probably noticed that I have been assigning descriptive variable names when declaring variables that help to identify their purpose or contents. This makes program code easier to read and understand. You also might have noticed that I am preceding each variable name with a three-character prefix that identifies the type of data associated with the variable, making things easier to understand. I recommend that you follow a similar approach when naming your own variables. For your convenience, you might want to use the prefixes shown in the following list:

  • Boolean: bln

  • Boolean: f (for a flag that is turned on and off)

  • Byte: byt

  • Date: dtm

  • Double: dbl

  • Error: err

  • Integer: int

  • Long: lng

  • Object: obj

  • Single: sng

  • String: str

image from book

Recognizing Variables as Objects

As you might recall from Chapter 1, "An Introduction to Visual C++ 2005 Express," Visual C++ is an object-oriented programming language. The object-oriented programming aspect is so deeply integrated into Visual C++ that even variables are treated like objects. Try the following example to see this concept in action:

  1. Start Visual C++ and create a new Visual C++ application.

  2. Double-click on the default form (form1) to open the Code Editor and access the form's Load event procedure.

  3. By default, Visual C++ generates the following code to set up the application's response to the Load event for you:

     private: System::Void Form1_Load(System::Object^ sender,           System::EventArgs^ e) { } 

  4. Declare a variable named intUserAge as an Int16 and assign it a value of 55, as shown here:

     private: System::Void Form1_Load(System::Object^ sender,           System::EventArgs^  e) {   Int16 intUserAge = 55; } 

  5. Next, type the following partial statement exactly as shown here:

     MessageBox::Show( intUserAge 

  6. Because Visual C++ treats variables as objects, IntelliSense kicks in and displays all the properties and methods available, as shown in Figure 5.7.

  7. Click on ToString and press Enter. The statement should look like the example shown here:

     MessageBox::Show( intUserAge.ToString() ); 

    Trick 

    You can use the ToString method to return a string showing the value for the specified variable, whether it is a number or a date.

image from book
Figure 5.7: Using IntelliSense to view methods and properties associated with a variable object.

Functions and Methods for Manipulating Strings

Because most people deal with information in the form of text more than in the form of numbers, the String data type is one of the most useful aspects of Visual C++. Technically, parts of this data type are a little too advanced to cover at this point. But as you can see from past chapter games and examples, the String data type is so useful that we had to start using it even before we understood it.

Hint 

A string is a series of one or more characters, which might include alphabetic, numeric, and special characters, in addition to spaces. It is defined by enclosing the characters within a pair of double quotation marks ("").

Let's look at some basic aspects of the String data type first. A variable with a data type of String can store up to 2 billion characters. The actual limit depends on your system's available memory, although for most purposes, you will probably never need to approach that limit.

A String data type has such a range because it is declared in a way that gives it access to more memory resources than a normal variable. A String makes use of the gcnew keyword to gain access to this memory. At this point, it is too early to cover gcnew in detail, but it is discussed in depth in Chapter 8, "Enhancing Code Structure and Organization." For now, just know that it is a way of giving certain data types access to the memory they need.

Hint 

gcnew is a new Visual C++ operator that gives variables access to memory resources that are managed by the .NET Framework, with support for garbage collection (a feature of .NET that takes care of freeing memory automatically). If you prefer to use the C++ standard new operator, you may use it instead of gcnew and take care of freeing memory yourself.

Declaring String Variables

Unlike other .NET languages such as Visual Basic, Visual C++ does not automatically manage strings. Programmers must go through a few extra steps to use them. The .NET Framework does simply use them, however, after you get the hang of how they work.

You declare a String data type using the following format:

 String^ strVariableName = gcnew String( "" ): 

There are three important elements to creating a string in Visual C++. First, note the special symbol before the variable, called p-hat (^). This symbol denotes that strVariableName is a handle, a special type of variable that can reference large sections of memory. As with gcnew, the details of handles are discussed in greater detail in Chapter 8.

Following gcnew, you see a repetition of the String data type. However, this data type has a special format. The parentheses and quotes are how the String data type is setting its starting value. You can place any text you like within the quotes. Empty quotes (two quotation marks side by side) indicate that the string has no initial value or is empty. You can, however, place text between the quotes, as in the next example:

 String^ strWelcome = gcnew String( "Welcome!" ); 

This line of code creates a variable (technically a handle) called strWelcome of type String. This variable is then attached to memory resources created by gcnew. The memory resource created by gcnew contains the text value of Welcome.

If this is a bit fuzzy at this point, an example should help to clear things up.

  1. Start Visual C++ and create a new Visual C++ application.

  2. Double-click on the default form (form1) to open the Code Editor and access the form's Form1_Load event procedure.

  3. By default, Visual C++ generates the following code to set up the application's response to the Load event for you:

     private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^  e) { } 

  4. Add the following code, which declares a variable of String type named strWelcomeMessage and initializes it with Welcome to the application! The result is then displayed in a dialog box.

     private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^  e) {   String^ strWelcomeMessage = gcnew String(   "Welcome to the application!" );   MessageBox::Show( strWelcomMessage ); } 

  5. Run the application. You see text in quotes.

  6. To illustrate how strings can be assigned values, add the following text, shown in bold, to the Form1_Load function:

     private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {   String^ strWelcomeMessage = gcnew String(   "Welcome to the application!" );   MessageBox::Show( strWelcomeMessage  );   strWelcomeMessage = "";   MessageBox::Show( strWelcomeMessage );   strWelcomeMessage = "Have a nice day!";   MessageBox::Show( strWelcomeMessage ); } 

  7. Run the program. You see the first welcome dialog box, followed by a blank dialog box. This is the result of the strWelcomeMessage = ""; line of code. When you select the OK button, you are taken to the last line, which presents another message.

Using Built-In String Methods

One of the great strengths of Visual C++ is the abundance of string manipulation methods that it provides. Visual C++ offers several ways to change the text that your application displays. In fact, the language provides so many different ways of manipulating strings that it is unlikely you will ever need to develop your own custom string-handling functions.

In previous chapters, you saw a number of examples of strings being used to convey information. Visual C++ provides a number of other string manipulation tools, including the properties and methods listed in Table 5.2.

Table 5.2: String Handling Properties and Methods

String Object Methods

Description

String::ToLower

Converts a string to all lowercase

String::ToUpper

Converts a string to all uppercase

String::Length

Retrieves the length of a string

String::SubString

Extracts a portion of a string

String::ConCat

Combines two strings

String::Chars

Searches for one string within another string

String::TrimStart

Removes leading blank spaces from the left side of a string

String::TimeEnd

Removes trailing blank spaces from the right side of a string

As a quick example of how to use these functions and methods, look at the following example:

 private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)  {         String^ strMsg =         gcnew String("Once upon a time in a very far away land" );         MessageBox::Show( "String is " + strMsg->Length +         " characters long." );         strMsg = String::Concat( strMsg, " there lived a giant." );         MessageBox::Show( "String is now " + strMsg->Length         + " characters long." ); } 

In this example, the Length property displays the number of characters that make up the strMsg variable's value. The value increases after String::Concat is called because this method adds strings together. In this case, strMsg is being set to equal the addition of itself (the second strMsg) and a new text string.




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net