Declaring Variables


Declaring Variables

You learned in Chapter 2 that the information a program uses while it is running first needs to be stored in memory. You need to reserve memory before you can store information there. You reserve memory by declaring a variable.

Declaring a variable not only reserves memory, but also gives you a convenient way of referring to that reserved memory when you need to do so in your program. You also learned in Chapter 2 that memory addresses have hexadecimal values such as 0012FED4. These values are hard to remember. It is much easier to remember information that, for example, relates to a test score by the name testScore. By declaring a variable, you can refer to the reserved memory by the variable s name , which is much easier to remember and identify with the stored information than is the hexadecimal address.

While declaring a variable is relatively simple, requiring only one line of code, much is happening behind the scenes. The program at the end of this section will show you how to determine the address and size of the memory reserved by declaring a variable.

Syntax of Declaring Variables

You have to declare a variable before you can use it. Declaring a variable involves the following syntax:

 [data type] [variable name] ; 

The data type may be any of the ones discussed in Chapter 2, including int, float, bool, char, or string. The data type tells the computer how much memory to reserve. As you learned in Chapter 2, different data types have different sizes in bytes. If you specify a data type with a size (on your compiler and operating system) of 4 bytes, then the computer will reserve 4 bytes of memory.

You choose the variable name; how you name a variable is discussed later in the section Naming the Variable. The name is an alias by which you can refer in code to the area of reserved memory. Thus, when you name a variable that relates to a test score testScore, you can refer in code to the reserved memory by the name testScore instead of by a hexadecimal value such as 0012FED4.

Finally, the variable declaration ends with a semicolon. The semicolon tells the compiler that the statement has ended. You can declare a variable either within a function, such as main, or above all functions, just below any include directives. Since for now our programs have only one function, main, we will declare all variables within main. When our programs involve more than one function, we will revisit the issue of where to declare variables.

The following statement declares in main an integer variable named testScore.

 int main(void) {  int testScore;  return 0; } 
Note  

Unlike the code in Chapters 1 and 2, there is no include directive such as #include < iostream > in this code because this code does not use cout or another function defined in a standard library file.

You will receive a compiler error if you refer to a variable before declaring it. In the following code, the reference to testScore will cause the compiler error undeclared identifier.

 int main(void) {  testScore;  int testScore;  return 0; } 

This compiler error will occur even though the variable is declared in the very next statement. The reason is that the compiler reads the code from top to bottom, so when it reaches the first reference to testScore, it has not seen the variable declaration.

This undeclared identifier compiler error is similar to the one in the Hello World! project in Chapter 1 when we (deliberately) misspelled cout as Cout. Since testScore is not a name built into C++, like main and int, the compiler does not recognize it. When you declare a variable, then the compiler recognizes further references to the variable name as referring to the variable that you declared.

Declaring Multiple Variables of the Same Data Type

If you have several variables of the same data type, you could declare each variable in a separate statement.

 int testScore;  int myWeight;  int myHeight; 

However, if the variables are of the same data type, you don t need to declare each variable in a separate statement. Instead, you can declare them all in one statement, separated by commas. The following one statement declares all three integer variables:

 int testScore, myWeight, myHeight; 

The data type int appears only once, even though three variables are declared. The reason is that the data type qualifies all three variables, since they appear in the same statement as the data type.

However, the variables must all be of the same data type to be declared in the same statement. You cannot declare an int variable and a float variable in the same statement. Instead, the int and float variables would have to be declared in separate statements.

 int testScore;  float myGPA; 

Naming the Variable

Variables, like people, have names , which are used to identify the variable so you can refer to it in code. There are only a few limitations on how you can name a variable.

  • The variable name cannot begin with any character other than a letter of the alphabet (A “Z or a “z) or an underscore (_). Secret agents may be named 007, but not variables. However, the second and following characters of the variable name may be digits, letters , or underscores.

  • The variable name cannot contain embedded spaces, such as My Variable, or punctuation marks other than the underscore character (_).

  • The variable name cannot be the same as a word reserved by C++, such as main or int.

  • The variable name cannot have the same name as the name of another variable declared in the same scope. Scope is an issue that will be discussed in Chapter 8. For present purposes, this rule means you cannot declare two variables in main with the same name.

Besides these limitations, you can name a variable pretty much whatever you want. However, it is a good idea to give your variables names that are meaningful. If you name your variables var1, var2, var3, and so on, up through var17, you may find it difficult to later remember the difference between var8 and var9. And if you find it difficult, imagine how difficult it would be for a fellow programmer, who didn t even write the code, to figure out the difference.

In order to preserve your sanity , or possibly your life in the case of enraged fellow programmers, I recommend you use a variable name that is descriptive of the purpose of the variable. For example, testScore is descriptive of a variable that represents a test score.

The variable name testScore is a combination of two names: test and score. You can t have a variable name with embedded spaces such as test score. Therefore, the two words are put together, and differentiated by capitalizing the first letter of the second word. By the convention I use, the first letter of a variable name is not capitalized.

Naming Conventions

A naming convention is simply a consistent method of naming variables. There are a number of naming conventions. In addition to the one I described earlier, another naming convention is to name a variable with a prefix, usually all lowercase and consisting of three letters, that indicate its data type, followed by a word with its first letter capitalized, that suggests its purpose. Some examples:

  • intScore    Integer variable representing a score, such as on a test.

  • strName    String variable representing a name, such as a person s name.

  • blnResident    Boolean variable, representing whether or not someone is a resident.

It is not particularly important which naming convention you use. What is important is that you use one and stick to it.

The Address Operator

Declaring a variable reserves memory. You can use the address operator (&) to learn the address of this reserved memory. The syntax is

 &[variable name] 

For example, the following code outputs 0012FED4 on my computer. However, the particular memory address for testScore on your computer may be different than 0012FED4. Indeed, if I run this program again some time later, the particular memory address for testScore on my computer may be different than 0012FED4.

 #include <iostream> using namespace std; int main(void) {  int testScore;  cout << &testScore;  return 0; } 

The address 0012FED4 is a hexadecimal (Base 16) number. As discussed in Chapter 2, memory addresses usually are expressed as a hexadecimal number.

The operating system, not the programmer, chooses the address at which to store a variable. The particular address chosen by the operating system depends on the data type of the variable, how much memory already has been reserved, and other factors.

You really do not need to be concerned about which address the operating system chose since your code will refer to the variable by its name, not its address. However, as you will learn in Chapter 11 when we discuss pointers, the address operator can be quite useful.

Using the Address and sizeof Operators with  Variables

The amount of memory reserved depends on a variable s data type. As you learned in Chapter 2, different data types have different sizes.

In Chapter 2, you used the sizeof operator to learn the size (on your compiler and operating system) of different data types. You also can use the sizeof operator to determine the size (again, on your compiler and operating system) of different variables.

The syntax for using the sizeof operator to determine the size of a variable is almost the same as the syntax for using the sizeof operator to determine the size of a data type. The only difference is that the parentheses following the sizeof operator refers to a variable name rather than a data type name.

The following code outputs the address and size of two variables:

 #include <iostream> using namespace std; int main(void) {  short testScore;  float myGPA;  cout << "The address of testScore is "  << &testScore << "\n";  cout << "The size of testScore is "  << sizeof(testScore) << "\n";  cout << "The address of myGPA is " << &myGPA << "\n";  cout << "The size of myGPA is "  << sizeof(myGPA) << "\n";  return 0; } 

The output when I ran this program (yours may be different) is

 The address of testScore is 0012FED4 The size of testScore is 2 The address of myGPA is 0012FEC8 The size of myGPA is 4 

Figure 3-1 shows how memory is reserved for the two variables. Due to the different size of the variables, the short variable, testScore, takes up two bytes of memory, and the float variable, myGPA, takes up four bytes of memory.

click to expand
Figure 3-1: Memory reserved for declared variables

As Figure 3-1 depicts, the addresses of the two variables are near each other. The operating system often attempts to do this. However, this is not always possible, depending on factors such as the size of the variables and memory already reserved. There is no guarantee that two variables will even be near each other in memory.

In Figure 3-1, the value for both memory addresses is unknown. That is because we have not yet specified the values to be stored in those memory locations. The next section shows you how to do this.




C++ Demystified(c) A Self-Teaching Guide
C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
EAN: N/A
Year: 2006
Pages: 148

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