Defining Arrays Using Constants

In the quiz example, the number of array elements has been set by either using a literal value (answers[3]) or by letting C make that determination when values are assigned. Each method works, but it's allowed—even recommended—that you simplify this process by using a constant to represent the number of array elements.

Constants were introduced in Chapter 2, “Introduction to Data Types.” You'll recall that C supports two formats for constant definitions. The first is to use the const keyword before defining the variable:

const int NUM = 10;
float gpas[NUM];

The second method is to define the constant using a preprocessor directive outside of the main function:

#define NUM 10

You'll learn more about preprocessor ...

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.