Using Constants

One of the classic tips for creating readable code is to avoid the use of magic tokens: literal values (such as a number) that are generally meaningless without some context. Here is an example of bad programming form:

if (num < 90) {
   // Do this.
}

Although you probably knew why num had to be less than 90 when you wrote the application, that's exactly the kind of thing you'll forget when revisiting the code some time later. Moreover, there's little chance of another programmer comprehending the meaning of that number.

A constant is a macro that defines a literal value. You can then use the constant whenever you would otherwise use the value. By using constants instead of literal values, you ensure that you or anyone else who reads your code sees a more meaningful description, like A_LEVEL instead of a mysterious 90 literal:

#define A_LEVEL 90
int main (void) {
   if (num < A_LEVEL) { ...
   // Rest of main function.

Another common use of constants is for setting the dimension of an array. You saw an example of this in Chapter 6, “Working with Arrays,” and you'll go through another one here.

To create a constant

1.
Create a new text file in your IDE or text editor.

2.
Begin with your standard comments and the #include directive (Script 8.2):

/* yards.c - Script 8.2 */
#include <stdio.h>

Script 8.2. Using constant macros, like NUM_ELEMENTS here, for array elements is a common and prudent practice.


3.
Add a #define directive to create a constant macro:

#define NUM_ELEMENTS 10

This directive associates the value 10 with NUM_ELEMENTS. We added a comment (see the corresponding script) so that the purpose of this macro is clear.

4.
Define the main function:

int main (void) {

5.
Create the necessary variables:

unsigned int yards[NUM_ELEMENTS];
int i;

The array yards will store a number of integers to be used later in converting yards to meters. It has been defined as an array that is NUM_ELEMENTS long. During the preprocessing stage, NUM_ELEMENTS will be replaced with its value (10).

The second variable, i, is an index variable to be used within two for loops.

6.
Use a for loop to populate the yards array:

for (i = 0; i < NUM_ELEMENTS; i++) {
     yards[i] = (i + 1) * 5;
}

This is a standard for loop for accessing every array element. Rather than refer to sizeof(yards) to know when to stop looping, you can more easily refer to the NUM_ELEMENTS value.

The contents of the loop assign increments of 5 to yards, starting at 5. So the first time the loop is run, i is 0, which means that (i + 1) * 5 is 5. On the next iteration, the calculation returns 10, and so on.

7.
Print a header for the forthcoming data:

printf ("%10s %10s
", "Yards",
 "Meters");

This table header uses spaces to make the data lay out nicely.

8.
Create another for loop in which each yard increment and its meters equivalent are printed:

 for (i = 0; i < NUM_ELEMENTS; i++) {
     printf ("%10d %10.2f
",
 yards[i], yards[i] * 0.9144);
}

The structure of the loop is the same as the previous loop. In the loop, the value of yards[i] is printed, along with that value times 0.9144, which calculates the meters equivalent. Again, padding is used so that the table has clean columns in the generated display.

9.
Complete the main function:

    getchar();
    return 0;
}

10.
Save the file as yards.c, compile, and debug.

11.
Run the executable (Figure 8.5).

Figure 8.5. A constant macro is referenced three times in the process of creating this result.


12.
Change the value of NUM_ELEMENTS, recompile, and rerun the application (Figure 8.6).

Figure 8.6. Changing the value of one macro constant creates a table of a different length.


✓ Tips

  • It is standard practice to name constants with all uppercase letters; this helps differentiate them from variables and other identifiers.

  • In a way, using constant macros is another method for working around variable scope. The preprocessor will replace every use of the macro anywhere in the C code—including inside functions—with its respective value. To be clear, this is not the intent of constant macros but only a result of how the preprocessor works.

  • When defining constants that will be used in several source files, consider putting all the macros in a single file. This helps ensure that you don't define a macro in multiple ways in separate files or have multiple macros representing the same logical value.

  • You may have caught another spot within the yards.c application where a constant macro would make sense: having a word like METERS_EQUIV represent the 0.9144 multiplication value.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset