[ Go back to normal view ]

BW2 :: the bitwise supplement :: http://www.bitwisemag.com/2

A Little Course in C. Part 3 – Constants and #define
Getting started with C programming

18 November 2013

by Huw Collingbourne

If you want to make sure that a value cannot be changed, you should declare a constant.



A constant is an identifier to which a value is assigned but whose value (unlike the value of a variable) should never change during the execution of your program. The traditional way of defining a constant is C is to use the preprocessor directive #define followed by an identifier and a value to be substituted for that identifier. Here, for example, is how I might define a constant named PI with the value 3.141593

#define PI 3.141593

In fact, the value of a constant defined in this way is not absolutely guaranteed to be immune from being changed by having a different value associated with the identifier. In C, the following code is legal (though your compiler may show a warning message):

#define PI 3.14159
#define PI 55.5

Modern C compilers provide an alternative way of defining constants using the keyword const, like this:

const double PI = 3.14159;

If I try to assign a new value to this type of constant the compiler won’t let me. It shows an error message, so this is not permitted:

const double PI = 3.14159;
const double PI = 55.5;

Probably most C programmers would use the #define version (as this has become the ‘traditional’ way of defining C constants). But in fact only the value assigned to the constant defined as a const is completely protected from being altered subsequently.

This course is based on my eBook, The Little Book Of C, which is provided with my multimedia online course, C Programming For Beginners.

Previous Lesson: Variables and Types

Next Lesson: Tests and Comparisons