Declaring a Variable


As mentioned earlier, variables have to be declared before they can be used. A simple declaration consists of a type, followed by one or more variable names separated by commas and terminated by a semicolon, as shown in this example:

int nPrimeNumber; double x, y, z;

Each variable can be given a qualifier before the type (for example, unsigned). You can also place an initializer after the variable name to give it an initial value (for example, int i = 0). The qualifier and the initializer are optional and don’t have to appear in the declaration, but the base type and variable name must be present. The declaration is terminated by a semicolon.

[qualifier] type name [initializer]; unsigned int i; // An unsigned integer variable i, note the // qualifier limiting the variable to // positive numbers. long lSalary = 0; // A long variable initialized to zero. double y; // A double variable without qualifier or // initializer

Declaring the variable enables the compiler to

  • Allocate enough memory to store the variable of that type and to associate the name of the variable with that memory location.

  • Reserve the name of the variable to prevent it from being used by other variables within the same scope.

    Note

    Scope refers to that part of the code where a variable is visible—where it can be used. The concept of scope is explained more in Chapter 4.

  • Ensure that the variable is used in a way consistent with its type. For example, if you have declared a variable as a char, you can’t store the value 3.7 in it.

Variable Naming

A C++ variable name can be any combination of letters, numbers, and underscores, as long as the first character of the variable name is a letter or an underscore. Although C++ does not place any restrictions on your choice of variable names, you should use meaningful variable names and be consistent in your naming conventions to increase the readability of your code. C++ is case- sensitive, meaning uppercase and lowercase letters are considered different; for example, myvariable and myVariable are two separate variables. However, it’s not a good idea to differentiate variables solely on the basis of case; doing so could lead to confusion. It would be easy to type a letter in the wrong case and end up using a completely wrong variable!

Note

As I mentioned in Chapter 1, it’s not a good idea to create identifiers that begin with two underscores or an underscore followed by a capital letter (for example, _A). Microsoft uses this naming convention to specify macros and Microsoft-specific keywords, so starting your variables with these combinations could lead to name conflicts.




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

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