In this exercise, you prevent a function from changing the value of a named constant passed to it.
a. If necessary, create a new project named Advanced23 Project and save it in the Cpp7\Chap10 folder. Copy the instructions from the Lab10-2.cpp file into a source file named Advanced23.cpp. (Alternatively, you can enter the instructions from Figure 10-35 into the Advanced23.cpp file.) Change the filename in the first comment to Advanced23.cpp.
b. The program passes the value of the UNIT_CHG named constant to the calcBill function, which stores the value it receives (.11) in the chgPerUnit variable. Because the function stores the value in a variable, the value can be changed by the function. First, you will verify that the calcBill function can change the value stored in its chgPerUnit variable. Insert a blank line above the totChg = numUnits * chgPerUnit; statement in the calcBill function. In the blank line, type chgPerUnit = .25;. Save and then run the program. Enter 3000 and 2000 as the current and previous readings, respectively. The program displays 1000 as the number of units used, which is correct. However, rather than displaying $110.00 as the total charge, the program displays $250.00.
c. To prevent the calcBill function from changing the charge per unit value, you must use the const keyword to indicate that the value being passed is a constant. Make the appropriate modification to the calcBill function’s prototype and its header. Save and then run the program. (If you are asked whether you would like to run the last successful build, click the No button.) The compiler displays an error message indicating that you cannot assign a value to the chgPerUnit variable, which is defined using the const keyword.
d. Delete the chgPerUnit = .25; statement from the calcBill function. Save and then run the program. Enter 3000 and 2000 as the current and previous readings, respectively. The program correctly displays 1000 and $110.00 as the units used and total charge, respectively.
Figure 10-35
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.