I l@ve RuBoard |
![]() ![]() |
5.9 Constant and Reference Declarations
Sometimes
you want to use a value that does not change, such as const float PI = 3.1415926; // The classic circle constant Constants must be initialized at declaration time and can never be changed. For example, if we tried to reset the value of PI to 3.0 we would generate an error message: PI = 3.0; // Illegal Integer constants can be used as a size parameter when declaring an array: const int TOTAL_MAX = 50; // Max. number of elements in total list float total_list[TOTAL_MAX]; // Total values for each category Another special variable type is the reference type. The following is a typical reference declaration: int count; // Number of items so far int& actual_count = count; // Another name for count The special character & is used to tell C++ that actual_count is a reference. The declaration causes the names count and actual_count to refer to the same variable. For example, the following two statements are equivalent: count = 5; // "Actual_count" changes too actual_count = 5; // "Count" changes too In other words, a simple variable declaration declares a box to put data in. A reference variable slaps another name on the box, as illustrated in Figure 5-1. Figure 5-1. Reference variables![]() This form of the reference variable is not very useful. In fact, it is almost never used in actual programming. In Chapter 9, you'll see how another form of the reference variable can be very useful. |
I l@ve RuBoard |
![]() ![]() |