Sams Teach Yourself C in 21 Days

(singke) #1
can’t be modified when the program is executed. A value is initialized at the time of dec-
laration and is then prohibited from being changed. Here are some examples:
const int count = 100;
const float pi = 3.14159;
const long debt = 12000000, float tax_rate = 0.21;
constaffects all variables on the declaration line. In the last line,debtandtax_rateare
symbolic constants. As a side note, you should notice that in this example,debtwas
declared as a long and tax_ratewas declared as a float.
If your program tries to modify a constvariable, the compiler generates an error mes-
sage. The following code would generate an error:
const int count = 100;
count = 200; /* Does not compile! Cannot reassign or alter */
/* the value of a constant. */
What are the practical differences between symbolic constants created with the #define
directive and those created with the constkeyword? The differences have to do with
pointers and variable scope. Pointers and variable scope are two very important aspects
of C programming, and you will learn about them on Day 9, “Understanding Pointers,”
and Day 12.
Now take a look at a program that demonstrates variable declarations and the use of lit-
eral and symbolic constants. Listing 3.2 prompts the you to enter your weight and year
of birth. It then calculates and displays the your weight in grams and your age in the year


  1. You can enter, compile, and run this program using the procedures explained on
    Day 1, “Getting Started with C.”


54 Day 3

Most C programmers today use constinstead of #definewhen declaring
Note constants.

LISTING3.2 const.c—A program that demonstrates the use of variables and constants
1: /* Demonstrates variables and constants */
2: #include <stdio.h>
3:
4: /* Define a constant to convert from pounds to grams */
5: #define GRAMS_PER_POUND 454
6:
7: /* Define a constant for the start of the next century */
8: const int TARGET_YEAR = 2010;
9:

06 448201x-CH03 8/13/02 11:14 AM Page 54

Free download pdf