WORKING WITH CONSTANTS


When deciding whether to use a constant, variable, array, or structure to store a piece of data, it is best to look first at how the data is to be used. Data that is known at design time and that will not change during the execution of the application is defined best as a constant. This allows Visual C++ to work more efficiently with the data and provides you, the programmer, with a measure of safety against accidentally changing it.

Declaring Your Own Constants

By assigning data to a constant instead of to a variable, you eliminate the possibility that you might alter the data mistakenly later on in your application. Unlike with variables, Visual C++ bars you from making a change to a constant value. If you try to change the data assigned to a constant, Visual C++ flags it as an error when you test the execution of your application.

Constants make your application code easier to read. They prevent the syndrome in code known as "magic numbers," which often seem like arbitrary, out-of-the-blue values. Constants, at a glance, explain what they are doing in the code.

To declare a constant within Visual C++, you must use the const keyword using the syntax outlined here:

 const DataType ConstHame = Expression; 

ConstName represents the name that you assign to the constant. DataType identifies the type of data to be assigned to the constant, and Expression represents the value that is being assigned. To demonstrate how constants work, take a look at the following example:

 const Int16 cMaxPasswordChars = 8; MessageBox::Show( String::Concat( "Maximum password characters: ",                     cMaxPasswordChars.ToString() ) ); 

In this example, a constant named cMaxPasswordChars is declared with a data type of Int16 and is assigned a value of 8. The MessageBox:: Show method uses it as an argument specifying the pop-up maximum number of password characters, as shown in Figure 5.6.

image from book
Figure 5.6: By assigning a string to a constant, you can use it throughout your application without worrying that the value will change.

Trick 

As you might have noticed in the previous example, the letter c precedes the name of the constant. This is to help identify it as a constant. Prefacing constants with a c is a recommended naming convention. When used consistently, it helps make your constants stand out and your code easier to read.




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