Summary: in this tutorial, you
will learn how use C constants in your code to make your
code more readable and easy to maintain.
Introduction to C constants
C constants using C preprocessor
There
are a lot of cases you want to use a constant in your
code for example to calculate
the square of a circle you code as follows:
square = 3.14159 * diameter;
|
In the statement, the constant 3.14159 represents the constant
PI. Instead of putting constant in literal form, we can use symbolic constant
as below:
square = PI * diameter;
|
As you
see, the C constants make your
code readable and the symbolic
constants tell you not only the value but also its meaning. In addition, if a
constant is used in several places, it is better to use symbolic constant because
when you want to change its value you just have to change it in one place that
define the constant, see the below example:
1
|
total = net + TAXRATE * net;
|
Later
on if the tax rate changes,
you only have to change it in where it is defined.But how do you define
symbolic C constants? The first idea of defining a C constant is using C
preprocessor as follows:
#define PI 3.14159
|
||
#define TAXRATE 0.1
|
By
doing this, when your program compiled, the constant values 1.14159 and 0.1
will be substituted everywhere you used PI and TAXRATE. This feature is known
as compile time substitution. Those defined constants are called manifest
constants because when you run the program, all the substitutions have already
been made.
Note
that there is no equal sign between constant’s name and value and there is no
semicolon (;) at the end of the statement.
It is
highly recommended that you use constant name is upper case so when you see it
in code you know that it is a constant. The formula of defining a constant is
as follows:
#define CONSTANT_NAME value
|
C constants using const keyword
C90
officially added a second way to create symbolic constants using the constkeyword to declare a
constant. This approach is more flexible that using C preprocessor #define such
as you can use keyword const to declare an array, pointer…etc.Once the value of
a constant using const keyword has been initialized, its value cannot be changed
through the program. See the below example:
const double PI
= 3.14159;
|
||
const double TAXRATE
= 0.1;
|
No comments:
Post a Comment